合并两个表,排除相同的记录

时间:2016-01-05 11:29:09

标签: mysql sql

我有两张桌子:

T1 
A  
B  
C  
D

T2  
A  
B  
E  
F  
G  

现在我想要查询将这两个表合并但排除 同样的记录。输出表应该是:

T1T2 
C  
D  
E  
F  
G

怎么做?

4 个答案:

答案 0 :(得分:4)

您似乎需要FULL OUTER JOIN并排除常见部分。您可以使用以下方法进行模拟:

SELECT T1.col_name
FROM T1 
LEFT JOIN T2
  ON T1.col_name = T2.col_name
WHERE T2.col_name IS NULL
UNION
SELECT T2.col_name
FROM T2 
LEFT JOIN T1
  ON T1.col_name = T2.col_name
WHERE T1.col_name IS NULL;

SqlFiddleDemo

╔══════════╗
║ col_name ║
╠══════════╣
║ C        ║
║ D        ║
║ E        ║
║ F        ║
║ G        ║
╚══════════╝

更多信息:Visual Representation of SQL Joins

enter image description here

SELECT <select_list>
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.Key = B.Key
WHERE A.Key IS NULL OR B.Key IS NULL

不幸的是MySQL不支持FULL OUTER JOIN所以我使用了LEFT JOIN的联合。

enter image description here

enter image description here

来自http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

的所有图片

附录

  

但是,如果我有两个不同列的不同表,但它们都有一个相同的列怎么办?使用的SELECT语句具有不同的列数

您可以使用其他列轻松扩展它。

SELECT 'T1' AS tab_name, T1.col_name, T1.col1, NULL AS col2
FROM  T1
LEFT JOIN  T2
  ON T1.col_name=  T2.col_name
WHERE T2.col_name IS NULL
UNION
SELECT 'T2' AS tab_name, T2.col_name, NULL, T2.col2
FROM  T2
LEFT JOIN  T1
  ON T1.col_name=  T2.col_name
WHERE T1.col_name IS NULL;

LiveDemo

输出:

╔══════════╦══════════╦══════╦═════════════════════╗
║ tab_name ║ col_name ║ col1 ║        col2         ║
╠══════════╬══════════╬══════╬═════════════════════╣
║ T1       ║ C        ║    3 ║                     ║
║ T1       ║ D        ║    4 ║                     ║
║ T2       ║ E        ║      ║ 2016-01-03 00:00:00 ║
║ T2       ║ F        ║      ║ 2016-01-02 00:00:00 ║
║ T2       ║ G        ║      ║ 2016-01-01 00:00:00 ║
╚══════════╩══════════╩══════╩═════════════════════╝

答案 1 :(得分:1)

我看到两种可能的解决方案。

UNION ALL与带GROUP BY x HAVING COUNT(x) = 1的外部选择一起使用:

SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT a FROM t2) as t12 GROUP BY a HAVING COUNT(a) = 1

使用UNION组合通过子查询过滤的两个SELECT

(SELECT a FROM t1 WHERE a NOT IN (SELECT a FROM t2)) UNION (SELECT a FROM t2 WHERE a NOT IN (SELECT a FROM t1))

不确定哪一个效果最好!

See it in action here

答案 2 :(得分:0)

尝试将两个表相交。你可以看到差异。

SELECT T1.col_name
FROM (
SELECT T1.col_name FROM T1
UNION ALL
SELECT T2.col_name FROM T2
) T1
GROUP BY col_name
HAVING count(*) = 1
ORDER BY col_name;

答案 3 :(得分:0)

假设两个表中没有重复项,一种方法使用select * from organisation where (3959 * acos(cos(radians(53.6771)) * cos(radians(lat)) * cos(radians(lon) - radians(-1.62958)) + sin(radians(53.6771)) * sin(radians(lat)))) < 800 和聚合:

union all

实际上,你可以放松没有重复的条件,但是你需要指定如何处理它们。