2

I'm building a little conjugation/radicalization app, and I have stumbled upon a problem. I have this SQL request:

SELECT    DISTINCT RA.* 
FROM      radical RA 
left join conjugated CO 
on        CO.word_id = RA.id 
where     CO.conjugation IN ('I', 'am', 'a', 'cat')

That returns:

| id | radical |
| 13 |  to be  |

However, I would like to get a result of the type:

| id   | radical | word |
| null |  null   |  I   |
|  13  | to be   | am   |
| null |  null   |  a   |
| null |  null   | cat  |

Does anyone know how?

StuartLC
  • 104,537
  • 17
  • 209
  • 285
Jo Colina
  • 1,870
  • 7
  • 28
  • 46

2 Answers2

1

You need a left join, but to start with all the words you want to keep:

select w.word, ra.* 
from (select 'I' as word union all
      select 'am' union all select 'a' union all select 'cat'
     ) w left join
     conjugated co
     on co.conjugation = w.word left join
     radical ra
     on ra.id = co.word_id;  

If these values are in conjugation, you can simply do:

select c.onjugation, ra.* 
from conjugated co left join
     radical ra
     on ra.id = co.word_id
where c.conjugation in ('I', 'am', 'a', 'cat') ;

That is, conjugation should be first, because you want to keep all matching rows in that table.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Seemingly you are using a Left Join, when you actually need a Right join (since it appears you want all rows of the right table matching the predicate to be returned)

So either switch the join:

SELECT    DISTINCT RA.*, co.`conjugated` as word
FROM      radical RA 
right join conjugated CO 
on        CO.word_id = RA.id 
where     CO.conjugation IN ('I', 'am', 'a', 'cat');

Or switch the order of the tables in the FROM:

SELECT    DISTINCT RA.*, co.`conjugated` as word
FROM      conjugated CO 
left join radical RA 
on        CO.word_id = RA.id 
where     CO.conjugation IN ('I', 'am', 'a', 'cat');
StuartLC
  • 104,537
  • 17
  • 209
  • 285