MySQL - 不显示任何重复行

时间:2017-03-09 08:29:01

标签: sql duplicates

我有两张桌子:

table1
id | column1
1  | a
2  | b
3  | c

table2
id | column1
1  | a
2  | b
3  | d

我只想显示:

3 |d
3 |c

到目前为止我尝试使用:

SELECT column1 FROM `table1` UNION DISTINCT SELECT column1 FROM `table2`

在结果中我有唯一的值,但我想要:如果有两个表中的重复值不显示任何值

编辑 抱歉,我在输出中遗漏了

5 个答案:

答案 0 :(得分:1)

select *
from
(
    select * from table1
    union all
    select * from table2
)
except all
(
    select * from table1
    intersect all
    select * from table2
)

第一个子查询(带UNION ALL)返回两个表中的所有行。

第二个子查询(带INTERSECT ALL)返回表的公共行。

获取所有行(UNION ALL结果)并使用INTERSECT ALL删除公共行(EXCEPT ALL行)。

答案 1 :(得分:0)

你想要实现这个目标吗?

SELECT ISNULL(table1.id, table2.id) AS id, ISNULL(table1.column1, table2.column1) AS column1
FROM table1
  FULL OUTER JOIN table2 ON table1.column1 = table2.column1
WHERE (table1.column1 IS NULL AND table2.column1 IS NOT NULL)
  OR (table1.column1 IS NOT NULL AND table2.column1 IS NULL);

如果没有,请提供更多关于重复的确切含义的数据和信息。

答案 2 :(得分:0)

所以你只想要你工会之外的价值观吗?

怎么样:

SELECT column1 FROM `table 1`, `table 2` 
MINUS (or EXCEPT, depending on your dbms)
SELECT column1 FROM `table1` UNION SELECT column1 FROM `table2`

答案 3 :(得分:0)

第一个查询显示table1中不存在于table2中的记录,第二个查询显示table2中不存在于table1中的记录。 Union all用于组合两个查询的结果集。

    select id, column from table1
    where (id, column) not in (select id, column from table2)
    union all
    select id, column from table2
    where (id, column) not in (select id, column from table1)

答案 4 :(得分:0)

解决方案很简单:  从table1中选择column1,其中column1不在(从table2中选择column1)

以上是MySQL的语法

谢谢你的缘故