在SELECT中忽略的MySQL DISTINCT显示重复

时间:2014-09-18 10:44:06

标签: mysql sql

我有以下查询正在连接3个表但显示重复的结果,其中我在r.Email列上使用DISTINCT只有一个记录实例。

SELECT DISTINCT FirstName, LastName, r.Email, ListingID, ListingFirmID
    FROM sancap_Residential_Property e 
    JOIN sancap_Agent r ON e.ListingAgentID=r.AgentID
    JOIN sancap_Office d ON e.ListingFirmID=d.firmID
    WHERE ListingFirmID != 'BrokerC'

数据看起来像这样,ListingID信息是唯一的,这就是我相信查询显示代理ID的原因。我该如何克服这个问题?

Buck      |     Rogers     |     buck@rogers.com     |     656565      |      BrokerAA
Buck      |     Rogers     |     buck@rogers.com     |     787878      |      BrokerAA
Pamm      |     Feeets     |     pamm@feeets.com     |     999999      |      BrokerBB

我想要的结果是:

Buck      |     Rogers     |     buck@rogers.com     |     656565      |      BrokerAA
Pamm      |     Feeets     |     pamm@feeets.com     |     999999      |      BrokerBB

2 个答案:

答案 0 :(得分:4)

最好尝试Group bymin()功能

SELECT FirstName, LastName, r.Email, min(ListingID) as ListingID, ListingFirmID
    FROM sancap_Residential_Property e 
    JOIN sancap_Agent r ON e.ListingAgentID = r.AgentID
    JOIN sancap_Office d ON e.ListingFirmID = d.firmID
    WHERE ListingFirmID != 'BrokerC'
GROUP BY FirstName, LastName, r.Email, ListingFirmID

通过上述查询,您将获得FirstName, LastName, r.Email, ListingFirmID的独特组合以及ListingID的最小值。

答案 1 :(得分:2)

试试这样。

SELECT FirstName, LastName, r.Email, ListingID, ListingFirmID
    FROM sancap_Residential_Property e 
    JOIN sancap_Agent r ON e.ListingAgentID=r.AgentID
    JOIN sancap_Office d ON e.ListingFirmID=d.firmID
    WHERE ListingFirmID != 'BrokerC'
group by FirstName, LastName, r.Email,ListingFirmID