从另一个表向查询添加条件

时间:2015-04-29 10:09:48

标签: sql tsql

我有这些表格: rome_sub(id_rome,id_sub)rome_holland(id_rome,id_holland)

我想做的是做一个像

这样的查询
SELECT * FROM rome_sub where id_sub=X

并加上这个条件:

id_holland IN (Y,Z)

2 个答案:

答案 0 :(得分:2)

您似乎在寻找EXISTS或IN子句:

select * 
from rome_sub 
where id_sub = 'X'
and id_rome in 
(
  select id_rome 
  from rome_holland 
  where id_holland in ('Y','Z')
);

或者:

select * 
from rome_sub 
where id_sub = 'X'
and exists 
(
  select *
  from rome_holland 
  where id_holland in ('Y','Z')
  and rome_holland.id_rome = rome_sub.id_rome
);

答案 1 :(得分:1)

JOIN两个表:

SELECT DISTINCT s.* 
FROM rome_sub AS s
INNER JOIN rome_holland AS h ON s.id_rome = h.id_rome
where s.id_sub = 'X'
  AND h.id_holland IN ('Y', 'Z');