需要Mysql自加入帮助

时间:2012-07-09 10:56:27

标签: mysql

我有以下表结构:

uid    | product_code
---------------------
00001  | 'tb'
00001  | 'im' 
00001  | 'ip'
00002  | 'tb'
00002  | 'im'

我想要一个selfjoin查询,它会向我显示那些包含所有三个产品代码'mg','ip','tb'的uid。即只显示00001。怎么办呢?

3 个答案:

答案 0 :(得分:2)

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'
如果您有更多产品代码,

也应该有用。

答案 1 :(得分:1)

select uid from mytable 
where product_code in ('mg','ip','tb') 
group by uid having count(distinct(product_code))=3;

答案 2 :(得分:0)

如果您只有三个产品代码 Select * from table group by uid having count(uid) = 3