现在两个表t1,t2,
t1中有两字段: t1_zd1,t1_zd2,
t2中有两个字: t2_zd1,t2_zd2,tyid.t2表字段t2_zd2的外表是t1表中的t1_zd1,t1表的数据如下:         
t1_zd1     t1_zd2
  8        工
  9        工
  10       在
  11       在t2表的数据如下:
t1_zd1   t1_zd2    tyid
  1       8         5
  2       8         7
  3       9         8
  4       9         8现在我需要检索t1表t1_zd1=8的记录 ,并且在t2表中 tyid=5且tyid=7的,这条sql语问怎么写啊。 

解决方案 »

  1.   

    并且在t2表中 tyid=5且tyid=7的???
    是 并且在t2表中 tyid=5或者tyid=7的把
    select t1.* from  t1 a 
    inner join t2 b on a.t1_zd1=b.t2_zd2 
    where a.t1_zd1=8 and (b.tyid=5 or b.tyod=7)
      

  2.   

    select t1_z 
    from( select a.t1_z  t1_z,
    count(1) n1,       --t1_z的个数
    sum(decode(b.tyid,5,0,7,1)) n2     --5是0,7是1
    from  t1 a, t2 b 
    where a.t1_zd1=b.t2_zd2 
    group by a.t1_z)
    where n1>=2      --t1_z在t2中至少存在2条
    and n1>n2     --个数大于和,说明不只有7还有5
      

  3.   


    select *
    from t1,t2
    where t1.t1_zd1=t2.t1_zd2 and t1.t1_zd1=8 and (t2.tyid=5 or t2.tyid=7)
    ps:为啥这么多贴都是才注册的号?刷*么?
      

  4.   

    select * from  t1 
    where t1.t1_zd1=8 and exists (select 1 from t2 where t1.t1_zd1=t2.t1_zd2 and tyid=5)
    and exists (select 1 from t2 where t1.t1_zd1=t2.t1_zd2 and tyid=7);
     
      

  5.   

    现在我需要检索t1表t1_zd1=8的记录 ,并且在t2表中 tyid=5且tyid=7的,这条sql语问怎么写啊。
    ???????????????
    且?????? 应该是 或吧。。貌似 且=与 吧
    如果是 ‘或’的话:
    select * from t1 a,t2 b 
    where a.t1_zd1=b.t2_zd2 and a.t1_zd1=8 and b.tyid in ('5','7')
     
      

  6.   

    sorry! 不小心写错了 。。
    select * from t1 a,t2 b 
    where a.t1_zd1=b.t2_zd2 and a.t1_zd1=8 and (b.tyid=5 or b.tyid=7) 
      

  7.   


    需求确实是:tyid=5且tyid=7,实际需求是:
    在表t1中检索出数据,但是检索出的数据必须在t2中的tyid=5且tyid=7。不知道这样说明白了没有啊!
      

  8.   


    看不懂是什么意思啊。实际需求是这样的:需要检索出t1表中的数据,但是这条数据在t2表中对应着两条数据(t2_zd2的外键是t1_zd1),且这两条数据的tyid=5且tyid=7。不知道我这样说清楚了吗?还请多多指教!
      

  9.   


    怎么可能是刷,哈哈,遇到这个问题快愁死了。实际需求是这样的:需要检索出t1表中的数据,但是这条数据在t2表中对应着两条数据(t2_zd2的外键是t1_zd1),且这两条数据的tyid=5且tyid=7。不知道我这样说清楚了吗?还请多多指教!
      

  10.   

    with ss as (
    select distinct * from t2 where tyid=5
    union all 
    select distinct * from t2 where tyid=7
    )
    select t1_zd2 from ss group by t1_zd2 having count(*)>1
      

  11.   

    你不是要检索检索t1表t1_zd1=8的记录
    select * from t1 where t1_zd1=8不就行了,你那tyid=5且tyid=7跟t1表又没啥关系。
      

  12.   

    谢谢大家的支持啊,问题已经解决了,我把积分平均分给大家,我的解决方案如下:select * from t1 where t1_zd1 in 
      (select t2_zd2  from t2 where 
     tyid in (5,7) GROUP by t2_zd2 having count(t2_zd2) = 2 )参照:http://hi.baidu.com/%C8%FD%C7%A7%B0%D7%B7%A2%B4%CB%B3%EE%B3%A4/blog/item/f227e00196a3aa0a738b657d.html