如何在没有重复行的情况下执行左联接SQL

时间:2020-10-20 14:50:02

标签: mysql sql

我试图基于ID在两个表之间执行联接(我需要第一个表中的所有列,而右表中仅一个列),由于某些原因,联接在创建的表上创建重复的行要大得多比左表 例如:

铅桌:

|lead_id  |owner   |status
----------------------------
|10002    |Jhon    |won
|10003    |David   |lost
|10004    |Roy     |open

活动表:

|lead_id  |owner   |activity
----------------------------
|10002    |Jhon    |sales
|10002    |Jhon    |sales
|10003    |David   |marketing 
|10004    |Roy     |manager
|10004    |Roy     |manager

我所需的结果是:

|lead_id |owner |activity  |status
----------------------------------
|10002   |Jhon  |sales     |won
|10003   |David |marketing |lost
|10004   |Roy   |manager   |open

相反,我得到的表中的行比“ Lead Table”中的行多 我的代码是:

SELECT
      d.*,
      a."activity" as "activity type"
FROM  "Deals Table" d
LEFT JOIN "Activity Table" a ON d."lead_id"  = a."lead_id"  

谢谢!!

3 个答案:

答案 0 :(得分:0)

要删除重复项,可以使用SELECT DISTINCT。但是,使用它时要小心,因为它可能会隐藏您实际要捕获的重复项。这也可能掩盖了您的加入条件太宽泛的事实。

SELECT DISTINCT 
      d.*,
      a."activity" as "activity type"
FROM  "Deals Table" d
LEFT JOIN "Activity Table" a ON d."lead_id"  = a."lead_id"  

答案 1 :(得分:0)

SELECT
      d.*,
      a."activity" as "activity type"
FROM  "Deals Table" d
LEFT JOIN (
select distinct lead_id  ,owner   ,activity
from "Activity Table" 
) as a
ON d."lead_id"  = a."lead_id"  

答案 2 :(得分:0)

使用非重复


SELECT distinct
      d.lead_id,
      d.owner,
      d.status,
      a."activity" as "activity type"
FROM  "Deals Table" d
LEFT JOIN "Activity Table" a ON d."lead_id"  = a."lead_id"  ;