简体   繁体   English

如何选择两个表的不同值?

[英]How can I select the distinct value of two tables?

I'm not sure it's possible but I would like to select the distinct value of two tables columns. 我不确定是否有可能,但是我想选择两个表列的不同值。

Consider table1 like: 考虑一下table1:

╔══════╗
║ col1 ║
╠══════╣
║ AAA  ║
║ AAA  ║
║ BBB  ║
║ BBB  ║
╚══════╝

and table2 like: 和table2一样:

╔══════╗
║ col1 ║
╠══════╣
║ AAA  ║
║ BBB  ║
║ CCC  ║
║ CCC  ║
╚══════╝

The output I would like would be: 我想要的输出将是:

AAA
BBB
CCC

Obviously something like: 显然是这样的:

SELECT DISTINCT table1.col1 , table2.col1 FROM table1 , table2;

won't work. 将无法正常工作。

SQLFiddle SQLFiddle

A simple UNION would do the tricks 一个简单的UNION就能解决问题

SELECT col1 FROM table1 
UNION 
SELECT col1 FROM table2;

There is no need to use the DISTINCT keyword as UNION already handle duplicates. 由于UNION已处理重复项,因此无需使用DISTINCT关键字。

FYI if you use UNION ALL the duplicates won't be handled anymore, then you would need to use DISTINCT . 仅供参考,如果您使用UNION ALL ,将不再处理UNION ALL重复项,那么您将需要使用DISTINCT

只需进行union完成工作,因为它将过滤出重复的记录。

SELECT col1 FROM table1 UNION SELECT col1 FROM table2

I don't usually go for sub-queries, but I think this is one of those times: 我通常不去子查询,但是我认为这是其中一次:

SELECT DISTINCT col1
FROM (SELECT col1 FROM table1 UNION SELECT col1 FROM table2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM