Join语句,但只需要根据WHERE表列获取数据为空

时间:2008-11-13 03:35:51

标签: sql mysql

我有这个查询语句,并希望只获取某个列为空的记录(volunteers_2009.venue_id

表格为volunteers_2009,我要查看的列是否为空:venue_id

以下是当前查询:

SELECT volunteers_2009.id, volunteers_2009.comments, 
   volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, 
   volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, 
   venues.venue_name 
FROM volunteers_2009 AS volunteers_2009 
LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) 
ORDER by $order $sort

我正在尝试这样做:

SELECT volunteers_2009.id, volunteers_2009.comments, 
   volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, 
   volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, 
   venues.venue_name 
FROM volunteers_2009 AS volunteers_2009 
LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) 
ORDER by $order $sort 
WHERE volunteers_2009.venue_id == ''

我如何只列出表格(venue_id)中包含空列(volunteers_2009)的记录?

2 个答案:

答案 0 :(得分:4)

空是你的意思是空吗?如果venue_id字段可以包含空值,那么您可以使用is运算符进行比较,如下所示:

WHERE volunteers_2009.venue_id is null

答案 1 :(得分:2)

WHERE子句在第二个查询中乱序。它必须在ORDER BY子句之前。

另外,我不认为你有任何空洞的场地。也许你真正想要的是:

SELECT volunteers_2009.id, volunteers_2009.comments, 
    volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, 
    volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, 
    venues.venue_name 
FROM volunteers_2009 
LEFT JOIN venues ON venue_id = venues.id
WHERE venues.id IS NULL
ORDER BY $order $sort

这将只带回志愿者_2009与任何场地都不匹配的记录。

或者这个:

SELECT volunteers_2009.id, volunteers_2009.comments, 
    volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, 
    volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, 
    venues.venue_name 
FROM venues
LEFT JOIN volunteers_2009 ON volunteers_2009.venue_id = venues.id
WHERE volunteers_2009.venue_id IS NULL
ORDER BY $order $sort

找到没有志愿者的场地。