2011-08-05 148 views
1

我有查詢在MySQL查詢選擇唯一行

SELECT DISTINCT employer.id, employer.name 
FROM employers 
LEFT JOIN positions ON positions.id = employers.id 
LEFT JOIN statuses ON statuses.position = positions.some 
WHERE statuses.number = 2 

而且就是一些我需要從僱主獨特的記錄,但我得到的重複,因爲statuses.number不重複像222 6 777等我需要搶他們只有一次。 我不想使用DISTINCT有沒有其他方法?

回答

3

使用GROUP BY statment

SELECT employer.id, employer.name 
    FROM employers 
    LEFT JOIN positions ON positions.id = employers.id 
    LEFT JOIN statuses ON statuses.position = positions.some 
    WHERE statuses.number = 2 GROUP BY employer.id 
0

僱主的ID使用GROUP BY,你只會得到一個僱主記錄返回的每一行:

SELECT employer.id, employer.name 
FROM employers 
LEFT JOIN positions ON positions.id = employers.id 
LEFT JOIN statuses ON statuses.position = positions.some 
WHERE statuses.number = 2 
GROUP BY employer.id 
+0

感謝我一直在尋找它 – Johnds

0

首先,任何時候你引用一個LEFT加入WHERE子句中的列,如statuses.number =2,您將否定LEFT並強制其表現得​​像INNER。

其次,試試這個版本:

SELECT e.id, e.name 
    FROM employers e 
    WHERE EXISTS(SELECT 1 
        FROM positions p 
         INNER JOIN statuses s 
          ON p.some = s.position 
        WHERE p.id = e.id 
         AND s.number = 2)