select * from wat_cominfo a 
left join Wat_ProComRelation b on b.Com_ID = a.Com_ID
where exists (select 1 from Wat_ProductInfo where Pro_Name = '苹果' and Pro_ID= b.Pro_ID)结果157条记录.
select * from wat_cominfo where Com_ID in(
select Com_ID from Wat_ProComRelation
where Pro_ID in (select top 1 Pro_ID from Wat_ProductInfo where Pro_Name = '苹果')
)结果88条记录.Wat_ProComRelation 是wat_cominfo(企业)和Wat_ProductInfo(产品)的关联表, 我要查询有"苹果"产品的企业.请问哪一个是正确的?? 有什么不同?? 其实我已经知道了, 只是想听听别人是怎么想的, 我以前一遇到关联表就用left join , 没有想过这样的问题. 努力学习!!!

解决方案 »

  1.   

    select a.Com_ID,b.……其它字段 from Wat_ProComRelation a left join wat_cominfo b on a.Com_ID=b.Com_ID left join Wat_ProductInfo c on a.Pro_ID=c.Pro_ID where c.Pro_Name='苹果'
    这样可能更直观一点,不知道楼主是不是这个意思。
      

  2.   


    select * from wat_cominfo where Com_ID in(
    select Com_ID from Wat_ProComRelation
    where Pro_ID = (select top 1 Pro_ID from Wat_ProductInfo where Pro_Name = '苹果')
    )同意楼上的,或者这样也可以。
    这样更容易扫描索引页,不会进行表扫描。
      

  3.   

    上面的代码贴错了select a.Com_ID,b.……其它字段 from Wat_ProComRelation a left join wat_cominfo b on a.Com_ID=b.Com_ID left join Wat_ProductInfo c on a.Pro_ID=c.Pro_ID where Pro_ID = (select top 1 Pro_ID from Wat_ProductInfo where Pro_Name = '苹果')
      

  4.   

    select * from wat_cominfo where Com_ID in(
    select Com_ID from Wat_ProComRelation
    where Pro_ID in (select top 1 Pro_ID from Wat_ProductInfo where Pro_Name = '苹果')--這邊top幹嘛?
    )
      

  5.   

    Left jion是以左边的表为根据查询出来的数据,看看你到底想要什么,再根据什么查询把
      

  6.   

    第一种方法是左连接,只要表wat_cominfo中有记录就会出现在结果中。
    第二种方法是内连接,需要com_id同时在两个表中存在,而且在Wat_ProComRelation中要满足给出的条件
    这是sql基本语法。
    还有右连接,交叉连接。