是否可以从一个表中选择值,它们在一个列表中不存在,但在另一个列表中存在...或者它们是否相反?
E.g。
SELECT COUNT(g.`property`) as `number`, g.`property`
FROM `foo` g
WHERE `theID` IS IN (SELECT `theID`
FROM `tableofIDS`
WHERE `theID` = '54252')
AND NOT IN (SELECT `theID`
FROM `anotherTableofIDS`
WHERE `theID` = '54252')
答案 0 :(得分:9)
SELECT COUNT(g.`property`) as `number`, g.`property`
FROM `foo` g
WHERE `theID` IN (SELECT `theID` FROM `tableofIDS` WHERE `theID` = '54252')
AND `theID` NOT IN (SELECT `theID` FROM `anotherTableofIDS` WHERE `theID` = '54252')
GROUP BY g.`property`
另外,您可以使用效果更好的联接:
SELECT COUNT(g.`property`) as `number`, g.`property`
FROM `foo` g JOIN (
SELECT `theID`
FROM `tableofIDS`
WHERE `theID` = '54252'
) id1 ON g.theID = id1.theID
LEFT JOIN (
SELECT `theID`
FROM `anotherTableofIDS`
WHERE `theID` = '54252'
) id2 ON g.theID = id2.theID
WHERE id2.theID IS NULL
GROUP BY g.`property`
答案 1 :(得分:0)
没有想到,但发现了2个语法错误。尝试
SELECT COUNT(g.`property`) as `number`, g.`property` FROM `foo` g WHERE `theID` IN (SELECT `theID` FROM `tableofIDS` WHERE `theID` = '54252') AND `theID` NOT EXISTS (SELECT `theID` FROM `anotherTableofIDS` WHERE `theID` = '54252')
修改:将NOT IN
更改为NOT EXISTS
答案 2 :(得分:0)
我想也许你正在寻找的只是这个:
SELECT COUNT(g.property) as `number`, g.property FROM foo g JOIN tableofIDs i USING (theID) RIGHT JOIN anothertableofIDs x USING (theID) WHERE g.theID = '54252' AND x.theID IS NULL GROUP BY g.property