MySQL的左联接,不等于应该只返回一行

时间:2020-10-26 10:13:00

标签: mysql sql subquery left-join where-clause

有人可以帮助我满足以下要求吗?

enter image description here

enter image description here

对于我在左联接查询下面写的上面两个表

select distinct result 
from a 
    left join b on a.number = b.reference 
where a.color='red' and b.value != '10'

此查询返回1和2作为输出。

但是我期望只有2作为输出,因为表b中的list1的值为:10,因此如果列表中的值匹配,则查询不应返回行。

4 个答案:

答案 0 :(得分:1)

我了解到,您希望a中的“红色”行在b中与value 10不匹配。我认为最好用not exists来表达:

select a.*
from tablea a 
where a.color = 'red' not exists (
    select 1
    from tableb b
    where b.reference = a.number and b.value = 10
)

答案 1 :(得分:1)

select distinct(result) from a where color='red' and
number not in (select reference from b where value =10)

答案 2 :(得分:1)

select result 
from a 
    left join b on a.number = b.reference AND b.value = 10
where a.color='red' and b.reference IS NULL

答案 3 :(得分:1)

可以使用left join进行此操作。但是过滤条件主要在on子句中:

select a.result 
from a left join
     b
     on a.number = b.reference and b.value = '10'
where a.color='red' and b.reference is null;