【问题标题】:SQL WHERE IN with Left Join is not returning all rows I expect带有左连接的 SQL WHERE IN 没有返回我期望的所有行
【发布时间】:2017-08-21 18:57:54
【问题描述】:

我正在构建一个小的共轭/激进化应用程序,但我偶然发现了一个问题。我有这个 SQL 请求:

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

返回:

| id | radical |
| 13 |  to be  |

但是,我想得到以下类型的结果:

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

有人知道怎么做吗?

【问题讨论】:

  • 请发布您的示例数据

标签: mysql sql where-in correspondence


【解决方案1】:

你需要一个left join,但要从你想保留的所有单词开始:

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;  

如果这些值在conjugation 中,您可以这样做:

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') ;

也就是说,conjugation 应该是第一个,因为您想保留该表中的所有匹配行。

【讨论】:

    【解决方案2】:

    看起来您正在使用Left 连接,而实际上您需要Right 连接(因为您似乎希望返回与谓词匹配的右表的所有行)

    所以要么切换加入:

    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');
    

    或者在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');
    

    【讨论】:

    • 您先生,救了我的命
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 2021-12-11
    • 2018-05-11
    相关资源
    最近更新 更多