查询无法按预期运行

时间:2012-08-10 10:40:52

标签: mysql sql database

以下是我正在尝试使用的查询,

select DISTINCT c.sno from Cards as c, reservation as r 
where c.name='CRS-4-FC' AND c.sno != r.ssno;

该查询应该只选择保留表中不存在的那些sno,即保留表中的ssno列中不存在sno。我投入了

c.sno!=r.ssno

所以我不选择所有的sno。但是当这个查询运行时,我得到所有的sno而不是那些没有保留的sno。有人可以帮我解决问题..

3 个答案:

答案 0 :(得分:2)

select DISTINCT c.sno
from Cards as c 
left outer join reservation as r on c.sno = r.ssno
where r.ssno is null
and c.name='CRS-4-FC'

答案 1 :(得分:1)

尝试LEFT JOIN代替:

SELECT DISTINCT c.sno
FROM Cards c
    LEFT JOIN reservation as r
        ON c.sno = r.ssno
WHERE c.name='CRS-4-FC' AND
      r.ssno IS NULL;

请参阅Visual Explanation of SQL Joins

答案 2 :(得分:1)

select DISTINCT c.sno 
from Cards as c LEFT JOIN reservation as r  
ON c.sno = r.ssno
where c.name='CRS-4-FC' AND r.ssno IS NULL;