现在两个表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语问怎么写啊。
------解决方案--------------------
- SQL code
并且在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)
------解决方案--------------------
- SQL code
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是1from 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
------解决方案--------------------
- SQL code
select *from t1,t2where t1.t1_zd1=t2.t1_zd2 and t1.t1_zd1=8 and (t2.tyid=5 or t2.tyid=7)
------解决方案--------------------
灰太狼和穷人说的都对
------解决方案--------------------
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);
------解决方案--------------------
现在我需要检索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')
------解决方案--------------------
------解决方案--------------------
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
------解决方案--------------------
你不是要检索检索t1表t1_zd1=8的记录
select * from t1 where t1_zd1=8不就行了,你那tyid=5且tyid=7跟t1表又没啥关系。