从union中选择不同的值

时间:2018-05-17 02:42:26

标签: sql distinct union

我有三张表(销售订单,发票,采购订单)

sales_order
------------
so_id (primary key)
item_id (foreign key)
entry_date

invoice
------------
invc_id (primary key)
item_id (foreign key)
entry_date

purchase_order
------------
po_id (primary key)
item_id (foreign key)
entry_date

它们都引用一个中心表(项目):

item_id (pk)

我正在尝试编写一个sql查询,该查询将返回日期范围内具有活动的所有项目。

这就是我提出的:

select distinct item_id from sales_order where entry_date between ? and ?
union
select distinct item_id from invoice where entry_date between ? and ?
union
select distinct item_id from purchase where entry_date between ? and ?

我认为这是正确的解决方案,但我不确定如何测试它。

问题1: 是"不同"关键字适用于所有语句还是仅适用于每个语句?即,每个查询将返回一个不同的集合,但是当你" union"它们在一起可以显示重复吗?

问题2: 有没有办法返回总(唯一)项目计数(作为单独的查询)?像:

select count(
    select distinct item_id from sales_order where entry_date between ? and ?
    union
    select distinct item_id from invoice where entry_date between ? and ?
    union
    select distinct item_id from purchase where entry_date between ? and ?
)

...

1 个答案:

答案 0 :(得分:1)

distinct是多余的。我经常写如查询:

select item_id from sales_order where entry_date between ? and ?
union  -- intentionally removing duplicates
select item_id from invoice where entry_date between ? and ?
union
select item_id from purchase where entry_date between ? and ?;

要返回总计数,您可以使用子查询:

select count(*)
from (select item_id from sales_order where entry_date between ? and ?
      union  -- intentionally removing duplicates
      select item_id from invoice where entry_date between ? and ?
      union
      select item_id from purchase where entry_date between ? and ?
     ) i;