MySQL:从 2 个不同的表中选择 Distinct?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1002452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL: Select Distinct from 2 different tables?
提问by JD Isaacks
I have 2 different tables that each have a column called product_type. How can I get the DISTINCT values of product_type across both tables? Just to clarify, if both tables have a product_type of "diamond" I only want it returned once. Basically as if both tables where combined and I selected distinct product_type from it.
我有 2 个不同的表,每个表都有一个名为product_type的列。如何在两个表中获取 product_type 的 DISTINCT 值?澄清一下,如果两个表的 product_type 都是“diamond”,我只希望它返回一次。基本上就好像两个表组合在一起,我从中选择了不同的 product_type 。
Thanks!!
谢谢!!
回答by albertein
Use a distinct with a subquery which contains a union
对包含联合的子查询使用不同的
select distinct product_type from (
select product_type from table 1
union
select product_type from table 2
) t
回答by Guffa
Use distinct and union:
使用 distinct 和 union:
select distinct product_type from table1
union
select distinct product_type from table2
The union will remove duplicates when combining the results.
合并结果时,联合将删除重复项。
回答by tekBlues
Note that the UNION clause returns unique values of the field, when you want it to return ALL the values you must use UNION ALL...
请注意,UNION 子句返回该字段的唯一值,当您希望它返回所有值时,您必须使用 UNION ALL...
select product_type from table_a
union
product_type from table_b