我有这些表
Customers
CustomerNumber date
001 8/1/2017
002 8/2/2017
003 8/3/2017
Tags
Index Tag Description
1 NEW New customer
2 OTHER Some other tag
Customers_Tags
TagIndex CustomerNumber
1 001
1 002
2 002
2 003
如何在单个查询中为所有客户提供标签1以及客户拥有的任何其他标签?因此,如果寻找标签1得到:
customer tag date
001 1 8/1/2017
002 1 8/2/2017
002 2 8/2/2017
答案 0 :(得分:2)
当该客户拥有索引1的标记时,使用exists()
获取所有客户和代码:
select ct.customernumber, ct.tagindex, c.date
from customers c
inner join customers_tags ct
on c.customernumber = ct.customernumber
where exists (
select 1
from customers_tags i
where i.customernumber = ct.customernumber
and i.tagindex = 1
)
或使用in()
:
select ct.customernumber, ct.tagindex, c.date
from customers c
inner join customers_tags ct
on c.customernumber = ct.customernumber
where c.customernumber in (
select i.customernumber
from customers_tags i
where i.tagindex = 1
)