如何在WHERE CLAUSE中使用DISTINCT以避免重复的行返回

时间:2014-04-07 22:10:36

标签: mysql sql

此SQL查询的结果应返回一组6行。

SELECT baseFeeds.siteURL, feedFinishes.timeTaken, feedFinishes.timeSubmitted 
FROM feedFinishes 
LEFT OUTER JOIN baseFeeds 
ON feedFinishes.GUID = baseFeeds.GUID 
WHERE feedFinishes.nowDate = baseFeeds.nowDate 
AND baseFeeds.siteURL LIKE '%www.example.com%'

目前它返回18行,正确的6行重复3次。我认为解决这个问题的方法是让另一个WHERE子句类似于:

WHERE DISTINCT feedFinishes.ID

经过研究,我尝试过:

SELECT baseFeeds.siteURL, feedFinishes.timeTaken, feedFinishes.timeSubmitted 
FROM feedFinishes 
JOIN baseFeeds 
ON feedFinishes.GUID = baseFeeds.GUID 
WHERE baseFeeds.siteURL LIKE '%www.example.com%' AND feedFinishes.ID in
     (SELECT ID FROM feedFinishes GROUP BY ID HAVING COUNT(ID)=1);

讨论后发现here

唉,这仍然会返回18行。我相信答案类似于here

任何建议都将受到赞赏。

1 个答案:

答案 0 :(得分:4)

您应该应用group by条款。

SELECT 
baseFeeds.siteURL, feedFinishes.timeTaken, feedFinishes.timeSubmitted
FROM feedFinishes 
JOIN baseFeeds 
ON feedFinishes.GUID = baseFeeds.GUID 
WHERE baseFeeds.siteURL LIKE '%www.example.com%' 
GROUP BY
baseFeeds.siteURL, feedFinishes.timeTaken, feedFinishes.timeSubmitted