MySQL:从两个不同的表中选择不同的内容?

12

我有两个不同的表格,它们各自都有一个叫做product_type的列。我该如何获取这两个表格中product_type的DISTINCT值?为了澄清一下,如果两个表格都有一个产品类型为“钻石”的product_type,我只想要它返回一次。基本上就像把这两个表合并起来,并从中选择不同的product_type一样。

谢谢!

3个回答

28
使用包含union的子查询进行去重。
select distinct product_type from (
    select product_type from table 1
    union 
    select product_type from table 2
) t

谢谢,有一个问题..那个“t”应该在末尾吗?它是用来做什么的?谢谢! - JD Isaacks
T是子查询的别名,因此您可以说t.product_type,并且它将意味着“来自称为T的子查询的product_type字段”。 - albertein
1
你需要外部查询吗?我认为UNION只会返回不同的行。(UNION ALL需要外部查询) - James Moore
@JamesMoore 是的,否则DISTINCT将不会被应用。 - sieppl

9

使用distinct和union:

select distinct product_type from table1
union
select distinct product_type from table2

当合并结果时,union将删除重复项。


1
请注意,UNION子句返回字段的唯一值,如果您希望它返回所有值,则必须使用UNION ALL...
select product_type from table_a
union
product_type from table_b

1
我认为这不会起作用。你漏掉了第二个表的SELECT语句。 - Shaq

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接