MySQL Union查询重复/分组依据

时间:2014-03-21 19:53:13

标签: mysql sql

(SELECT * FROM Reports WHERE Modulo = "Reports" ) UNION ( SELECT * FROM Reports_Copy WHERE Modulo = "Reports" );

我有两个表,在联合时给我两个表中的结果,但我希望看到报告的结果以及报告副本中不是表格报告的那些。

tables
REPORTS
ID/Modulo/Name
1/REPORTS/JANE 
2/REPORTS/JOSE
3/REPORTS/ANA

REPORTS_COPY

ID|Modulo /Name
1 /REPORTS/JANE 
2 /REPORTS/JOSE
3 /REPORTS/ANA
4 /REPORTS/DAVID

RESULT ==
   (SELECT * FROM Reports WHERE Modulo = "Reports" ) UNION ( SELECT * FROM Reports_Copy WHERE Modulo = "Reports" );

ID/Modulo /Name
1 /REPORTS/JANE 
1 /REPORTS/JANE 
2 /REPORTS/JOSE
2 /REPORTS/JOSE
3 /REPORTS/ANA
3 /REPORTS/ANA
4 /REPORTS/DAVID

我想要的结果

ID|Modulo /Name
1 /REPORTS/JANE 
2 /REPORTS/JOSE
3 /REPORTS/ANA
4 /REPORTS/DAVID

2 个答案:

答案 0 :(得分:0)

您可以使用union执行此操作,只需过滤第二个子查询:

SELECT r.*
FROM Reports r
WHERE Modulo = 'Reports'
UNION ALL
SELECT rc.*
FROM Reports_Copy rc
WHERE Modulo = 'Reports' AND
      NOT EXISTS (SELECT 1 FROM REPORTS R WHERE RC.ID = R.ID);

答案 1 :(得分:0)

仅靠工会:

select * from REPORTS where Modulo = 'REPORTS'
union
select * from REPORTS_COPY where Modulo = 'REPORTS'

http://www.sqlfiddle.com/#!2/85439a/2