简体   繁体   English

在mysql查询中选择唯一的行

[英]Select unique rows in mysql query

I have 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

And the thing is some i need unique records from employers but i am getting duplicates because statuses.number do repeat like 222 6 777 etc i need to grab them only once. 而且事情是有些,我需要雇主提供独特的记录,但我却重复了,因为statuss.number确实像222 6 777这样重复,所以我只需要抓住它们一次。 I dont want to use DISTINCT is there other way? 我不想使用DISTINCT还有其他方法吗?

use the GROUP BY statment 使用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

Using GROUP BY on employer id, you will only get one employer record for each row returned: 在雇主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

First, any time you reference a LEFT JOINed column in your WHERE clause, like statuses.number =2 , you negate the LEFT and force it to behave like an INNER. 首先,每当您在WHERE子句中引用LEFT JOINed列(如statuses.number =2 ,都将否定LEFT并强制其表现为INNER。

Second, try this version: 第二,试试这个版本:

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