admin

加入客户和标签表

sql

我有这些表

    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

阅读 240

收藏
2021-07-01

共1个答案

admin

使用exists()让所有的客户和标签,当客户有指数1的标签:

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
  )
2021-07-01