user_id               product_id
1309051512660220 1005
1309051512660220 1006
1309051512660221 1007
1309051512660221 1009
1309051512660223 1010
1309051512660223 1012
1309051512660225 1016
1309051512660225 1021
1309051512660229 1038
1309051512660313 1000
1309051512660313 1003
1309051512660313 1005我的意思是同一个 user_id 下面有多个不同的product_id ,想查询同时有product_id = 1005 1006 的user_id.我的语句如下select * from t1 a
   where exists(select 1 from t1 where product_id = 1005 and user_id = a.user_id)
        and product_id = 1006
或者创建临时表 再做 in。 前一个方法效率太慢。特别是上千万数据量的时候,后一方法涉及到创建表也比较麻烦,有没有相对比较简单的方法呢?请大大们指教。

解决方案 »

  1.   

    子查询肯定是效率会低一些,你这里不需要用子查询的啊,你直接用in不好些吗?select t.user_id, t.product_id
    from t1 t 
    where t.product_id in(1005,1006);
      

  2.   

    select user_id from t1 where product_id =1005
    union select user_id from t1 where product_id =1006;
      

  3.   

    select t.user_id from t1 t 
    where t.product_id in(1005,1006)
    group by t.user_id having count(t.user_id) > 1;
      

  4.   

    select user_id from (select user_id,count(user_id) users from (select * from t where product_id=1005 or product_id=1006) group by user_id) where users>=2
      

  5.   


    楼主自己都只用了一个子查询,而你的这,子查询,子查询 group by......
      

  6.   

    select user_id from t where product_id=1005
    intersect
    select user_id from t where product_id=1006