sql左连接上的重复记录

时间:2017-12-04 13:09:25

标签: sql sql-server left-join

当我使用这个SQL查询时,没有重复的 shops.id

SELECT * 
FROM   shops 
LEFT JOIN expiration 
       ON shops.id = expiration.shopid 
ORDER  BY shops.id

但是当我使用这个(使用where语句)时,有许多重复的 shops.id

SELECT * 
FROM   shops 
LEFT JOIN expiration 
       ON shops.id = expiration.shopid 
WHERE  shops.ref = 9 
ORDER  BY shops.id 

为什么左连接会返回重复的行以及如何添加 导致此行?

2 个答案:

答案 0 :(得分:0)

看起来每个人都同意你在第一次查询时已经有重复但是你错过了。很容易测试

 SELECT 'shops', shops.id, COUNT(*)
 FROM shops
 GROUP BY shops.id
 HAVING COUNT(*) > 1

 UNION ALL      

 SELECT 'expiration ', expiration.shopid , COUNT(*)
 FROM expiration 
 GROUP BY expiration.shopid 
 HAVING COUNT(*) > 1

答案 1 :(得分:0)

您可以尝试选择Distinct

SELECT DISTINCT * 
FROM   shops 
LEFT JOIN expiration 
       ON shops.id = expiration.shopid 
WHERE  shops.ref = 9 
ORDER  BY shops.id 

没有数据就很困难。但这可能有所帮助。

另一种选择可能是包括左外连接:

  SELECT DISTINCT * 
    FROM   shops 
    LEFT OUTER JOIN expiration 
           ON shops.id = expiration.shopid 
    WHERE  shops.ref = 9 
    ORDER  BY shops.id 

希望它有所帮助。