如何从连接中删除重复的行(SQL)

时间:2014-01-27 04:22:11

标签: mysql sql join

我只需从三个表中获取唯一的行。我怎么能这样做?

我有一个SQL查询:

SELECT *
FROM l_req
LEFT JOIN p_req ON (p_req.uid = l_req.uid)
LEFT JOIN r_req ON (r_req.uid = l_req.uid)
WHERE l_req.uid = 100931362

表架构:

Table l_req

id column2 column3 uid

1     2      3      100931362
2     3      4      100931362
3     4      5      100931362

Table p_req

id column2 column3 uid

1     6      5      100931362

查询结果:

id column2 column3 uid              id1  column21 column31 uid1
1     2       3     100931362        1       6       5       100931362
2     3       4     100931362        1       6       5       100931362
3     4       5     100931362        1       6       5       100931362

=>我有一个来自JOIN的重复行。

我需要这样的结果:

id column2 column3 uid              id1  column21 column31 uid1
1     2       3     100931362        1       6       5       100931362
2     3       4     100931362        NULL    NULL    NULL    NULL
3     4       5     100931362        NULL    NULL    NULL    NULL

2 个答案:

答案 0 :(得分:1)

因为您的表结构看起来几乎相同,所以除了连接之外,还有其他选项。以下是使用unions

的可能解决方案

设置一个手工字段名称,用于标识行来自哪个表,以便在联合后区分,因为结果看起来都是相同的。

SELECT 'l_req' AS table_name, id, column2, column3, uid FROM l_req WHERE uid = 100931362
UNION ALL
SELECT 'p_req' AS table_name, id, column2, column3, uid FROM p_req WHERE uid = 100931362
UNION ALL
SELECT 'r_req' AS table_name, id, column2, column3, uid FROM r_req WHERE uid = 100931362

我还假设你的r_req表与其他表具有相同的结构。您可以期望此查询的结果可能如下所示:

table_name  id  column2 column3 uid
l_req       1   2   3   100931362
l_req       2   3   4   100931362
l_req       3   4   5   100931362 
p_req       1   6   5   100931362 -- this is your extra result original from join

答案 1 :(得分:0)

您可以尝试这样

Select id,column2,column3,Uid from
(
SELECT *
FROM l_req,ROW_NUMBER() OVER(PARTITION BY id,column2,column3 ORDER BY id ASC) AS RN
LEFT JOIN p_req ON (p_req.uid = l_req.uid)
LEFT JOIN r_req ON (r_req.uid = l_req.uid)
WHERE l_req.uid = 100931362
) AS T

Where RN = 1

<强>(OR)

Select Case when RN = 1 Then id Else Null End,
       Case when RN = 1 Then column2 Else Null End,
       Case when RN = 1 Then column3 Else Null End,
       Case when RN = 1 Then uid Else Null End
(
SELECT *
FROM l_req,ROW_NUMBER() OVER(PARTITION BY id,column2,column3 ORDER BY id ASC) AS RN
LEFT JOIN p_req ON (p_req.uid = l_req.uid)
LEFT JOIN r_req ON (r_req.uid = l_req.uid)
WHERE l_req.uid = 100931362
) AS T

希望这能帮到你