select t.* from t_customer_tel t
where exists
(select 1 from t_product p,t_query_recommend r
      where p.product_status='2'
      and p.product_spec_id in ('A101','A102')
      and p.product_id=r.product_id
      and p.customer_tel_id=t.customer_tel_id
 );
--结果记录为 29  select t.*--count(*)
  from t_customer_tel t, t_product p, t_query_recommend r
  where p.product_status='2'
  and p.product_spec_id in ('A101','A102')
  and p.product_id=r.product_id
  and p.customer_tel_id=t.customer_tel_id;
--结果记录为 108这2个sql为什么差距这么大呢,2个sql条件一样,为什么结果数量不对呢?

解决方案 »

  1.   

    t_product p, t_query_recommend r
    因为这两个表连接产生了重复的customer_tel_id
    因此结果大大增加你可以确认一下
    select count(1),count(distinct p.customer_tel_id)
      from t_customer_tel t, t_product p, t_query_recommend r
      where p.product_status='2'
      and p.product_spec_id in ('A101','A102')
      and p.product_id=r.product_id
      and p.customer_tel_id=t.customer_tel_id;
      

  2.   

    有可能是因为使用exists引起的。
      

  3.   

    这两个语句有可比性吗?这两个句子语义完全不一样,你拿来比什么用exists,指的是存在,也就是说,exist后面括号中的语句不管生成多少条记录,最后提交给前面的语句的时候是distinct过的,也就是说,是一个经过distinct的集合。比如,(10, 10 ,9, 8, 8)和(10, 9, 8)是等效的而关联的含义我就不多说了,这两者完全不一样,没有可比性
      

  4.   

    第一条
    最大记录数为t_customer_tel 记录数第二条
    最大记录数为笛卡尔集
      

  5.   

    2个sql明显不一样第一个只查询t_customer_tel表第二个查询t_customer_tel t, t_product p, t_query_recommend r三个表,他们联合后,主键不唯一,也就是说存在一对多,所以记录比较多
      

  6.   

    select t.* from t_customer_tel t
    where exists
    (select 1 from t_product p,t_query_recommend r
          where p.product_status='2'
          and p.product_spec_id in ('A101','A102')
          and p.product_id=r.product_id
          and p.customer_tel_id=t.customer_tel_id
     );
    --结果记录为 29其实这种写法相当于:select * from t_customer_tel
                      where customer_tel_id in 
                           (select customer_tel_id 
                                   from t_product p,
                                        t_query_recommend r
                                   where p.product_status='2'
                                         and p.product_spec_id in ('A101','A102')
                            )
         这样选出来的记录自然是不会超过t_customer_tel记录的条数。但是下面的查询时先做的是等值连接。是在笛卡尔积的基础上,判断p.customer_tel_id 和t.customer_tel_id相等的记录。这样自然就会多。比如p里面有两条记录的是同一个customer_tel_id,和T表做等值连接就会有两条记录。这就是原因!
      select t.*--count(*)
      from t_customer_tel t, t_product p, t_query_recommend r
      where p.product_status='2'
      and p.product_spec_id in ('A101','A102')
      and p.product_id=r.product_id
      and p.customer_tel_id=t.customer_tel_id;
    --结果记录为 108
      

  7.   


    第一个SQL用exists 意思是后面 select 1 from……查询出的结果在 t_customer_tel 表中存在的记录,t_customer_tel 表中不匹配的不列出来。
    第二个SQL就是表关联,三个表中每条记录都关联一下,数据当然多了。
      

  8.   

    t_customer_tel t中的t.customer_tel_id值在t_product p中存在多条记录