MYSQL:Left仅加入第一行或选择distinct

时间:2014-09-26 09:07:53

标签: mysql left-join

我试图在几张桌子上做左联。但是,它显示了所有左连接表结果。主表将是' a'但是它显示重复的id,因为它的id在其他表上存在多次。如何只选择其他表格的第一行?或者在表格中选择不同的结果' a' ?这是我的SQL

SELECT a.adsId, a.adsName, a.adsUrl, a.sourceFileName, c.userName, d.preferenceId, e.ppv FROM y5ads_new.ads_source a 
                INNER JOIN y5ads_new.campaign b ON a.campaignId=b.campaignId 
                INNER JOIN y5ads_new.system_member c ON b.createdBy=c.memberId
                INNER JOIN y5ads_new.ads_preference d ON a.adsId=d.adsId
                INNER JOIN y5ads_new.ads_rates e ON a.adsId=e.adsId
                WHERE a.status='2' AND a.deleted='False' AND CURDATE() BETWEEN a.startDate and a.endDate 
                AND b.status='2' AND b.deleted='False' AND CURDATE() BETWEEN b.startDate and b.endDate 
                AND d.deleted='False' AND CURDATE() BETWEEN d.startDate and d.endDate 
                AND e.is_active='1' AND CURDATE() BETWEEN e.startDate and e.endDate 
                ORDER BY a.adsId DESC, d.preferenceId DESC, e.id DESC

1 个答案:

答案 0 :(得分:2)

使您的ID不同并使用LEFT JOIN:

SELECT a.adsId, a.adsName, a.adsUrl, a.sourceFileName, c.userName, d.preferenceId, e.ppv 
FROM y5ads_new.ads_source AS a 
LEFT JOIN (SELECT DISTINCT campaignId as campaignId FROM y5ads_new.campaign) AS b 
ON a.campaignId=b.campaignId 
LEFT JOIN (SELECT DISTINCT memberId AS memberId, userName FROM y5ads_new.system_member) AS c 
ON b.createdBy=c.memberId
LEFT JOIN (SELECT DISTINCT adsId AS adsId, preferenceId FROM y5ads_new.ads_preference) AS d 
ON a.adsId=d.adsId
LEFT JOIN (SELECT DISTINCT adsId AS adsId, ppv FROM y5ads_new.ads_rates) AS e 
ON a.adsId=e.adsId
WHERE ...