簡體   English   中英

在mysql查詢中選擇唯一的行

[英]Select unique rows in mysql query

我有疑問

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

而且事情是有些,我需要雇主提供獨特的記錄,但我卻重復了,因為statuss.number確實像222 6 777這樣重復,所以我只需要抓住它們一次。 我不想使用DISTINCT還有其他方法嗎?

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

在雇主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

首先,每當您在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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM