在mysql查询中选择唯一的行

时间:2011-08-05 21:51:51

标签: mysql unique distinct

我有查询

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 个答案:

答案 0 :(得分:3)

使用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

答案 1 :(得分: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

答案 2 :(得分:0)

首先,无论何时在WHERE子句中引用LEFT JOINed列,如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)