从具有两个条件的表中选择

时间:2016-05-09 18:19:45

标签: sql

我遇到了疑问,我需要一些帮助。

我需要从表中选择满足其他表中两个条件的值,例如:

Select * from table1 
where ID =  (select ID from table2) 
AND value = (select value from table2)

所以,如果我只需要表中的一个值,我可以查询:

Select * from table1 where ID =  (id1) AND value = (value1)

我所知道的唯一解决方案是使用IN,但它不是请求的解决方案。

我需要类似的东西,但是计算table2返回的数据不仅是一行,而是多行。

有人能给我一些关于如何找到它的线索吗?

感谢。

3 个答案:

答案 0 :(得分:1)

一种方法使用exists

Select *
from table1 t1
where exists (select 1
              from table2 t2
              where t2.id = t1.id and t2.value = t1.value
             );

这是ANSI标准语法,因此它应该适用于任何数据库。有些数据库支持这种语法:

select t1.*
from table1 t1
where (t1.id, t1.value) in (select t2.id, t2.value from table2 t2);

答案 1 :(得分:1)

我会使用ANDOR

select * 
from table1 
where (ID =  (id1) AND value = (value1)) 
OR (ID =  (id2) AND value = (value2))

必须在括号中添加每项检查。这允许返回与对ID和VALUE匹配的所有结果。

答案 2 :(得分:1)

Select * from 
table1 inner join table2 on
(table1.ID = table2.ID and  
table1.value = table2.value) ;
  

因为据我所知,您只需要选择table1中的IDvalue table1等于IDvalue的所有行。在table2中{1}}。因此,您只需要inner join加入table1table2来检查条件。