oderID color
1 红色
1 黄色
2 红色
2 绿色
3 黄色
3 绿色
4 红色
4 黄色
查询color既有红色又有黄色的oderID
结果为 1
4 这个怎么写 各位大神
select orderid,color from table t1 where t1.color='红色' and exists (select 1 from table t2 where t2.color='黄色' and t1.orderid=t2.orderid);
select t1.oderID from t t1
where t1.color = '红色'
and exists
(select t2.* from t t2
where t2.oderID = t1.oderID and t2.color='黄色');
个人思路:**先查出**一种颜色的所有数据(oderID<你写的oderID>,color)比如**红色**,再在得到**红色的oderID中查找** 拥有**黄色**
的oderID
注:这里没有表名,假设为:A
解答:select oderID from A where color='黄色' and oderID in (select oderID from A where color='红色') as B
上面Zacharl道友用的exists 是一样的效果,exists一般用于B表的数据比A的数据大的时候,这样效率会快很多
若是A表的数据大于B表的数据,则用in
当然这里的效果都是一样
select oderID from A where color='黄色' or color='红色'
这个样子写应该没问题,不过也可以用两个select语句求并集,这样在使用时查询效率应该会高些
select * from a where color='红色' and color='黄色'