我有以下表结构:
uid | product_code
---------------------
00001 | 'tb'
00001 | 'im'
00001 | 'ip'
00002 | 'tb'
00002 | 'im'
我想要一个 selfjoin 查询,它将向我显示那些具有所有三个产品代码 'mg'、'ip'、'tb' 的 uid。即只显示00001。如何做呢?
我有以下表结构:
uid | product_code
---------------------
00001 | 'tb'
00001 | 'im'
00001 | 'ip'
00002 | 'tb'
00002 | 'im'
我想要一个 selfjoin 查询,它将向我显示那些具有所有三个产品代码 'mg'、'ip'、'tb' 的 uid。即只显示00001。如何做呢?
SELECT sj1.uid FROM tbl sj1
JOIN tbl sj2 ON sj1.uid = sj2.uid
JOIN tbl sj3 ON sj1.uid = sj3.uid
WHERE sj1.product_code = 'tb'
AND sj2.product_code = 'im'
AND sj3.product_code = 'mg'
如果您有更多产品代码,也应该可以使用。
select uid from mytable
where product_code in ('mg','ip','tb')
group by uid having count(distinct(product_code))=3;
如果您只有三个产品代码
Select * from table group by uid having count(uid) =
3