2011-02-17 71 views
2

是否可以從表中選擇值,它們不存在於一個列表中,但存在於另一個列表中,或者以其他方式存在周圍?mySQL:如何從表中選擇哪裏列表而不是在另一個列表

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

回答

8
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` 

Alternativly,您可以使用連接,這將有更好的表現:

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` 
+0

+1「聯合」方式實際上是更好的方式。即將編輯我的答案,包括它。 – fancyPants

+0

@WiseDonkey - 注意這兩個答案都有一個GROUP BY子句..MySQL通過不使它成爲必需的子句來對新手查詢作者造成破壞。您應該嘗試習慣編寫GROUP BY子句,因爲每個其他數據庫都需要GROUP BY子句。 – Leslie

+0

@leslie實際上,OP的查詢將會拋出一個錯誤:「混合GROUP沒有GROUP列是非法的bla bla bla',因爲即使MySql在有列和聚合函數的查詢時也會出錯,並且沒有組通過。 –

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 INNOT EXISTS

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 
相關問題