我有以下声明:
select region_id from regions
where region_name = 'Europe'
我需要在下面的语句中输出:'bla'是:
select count(*) from countries
where region_id = 'bla'
我该怎么做?
答案 0 :(得分:5)
select distinct * from countries
where region_id IN (select region_id from regions
where region_name = 'Europe')
答案 1 :(得分:2)
拯救的子查询!
select distinct *
from countries
where region_id=(select top 1 ir.region_id
from regions ir
where ir.region_name = 'Europe' )
或者,您可以使用in
并为其提供从查询中返回的项目列表。
答案 2 :(得分:2)
使用EXISTS:
SELECT c.*
FROM COUNTRIES c
WHERE EXISTS (SELECT NULL
FROM REGIONS r
WHERE r.region_id = c.region_id
AND r.region_name = 'Europe')
我的偏好是使用EXISTS而不是IN,因为:
IN
限制为1,000个值EXISTS
允许您在必要时匹配多个列EXISTS
在第一场比赛中返回true,根据需要可以比IN /等更快大多数人将EXISTS
误认为是一个相关的子查询,但它的执行方式不同&不评估SELECT
子句 - 您可以使用:
SELECT c.*
FROM COUNTRIES c
WHERE EXISTS (SELECT 1/0
FROM REGIONS r
WHERE r.region_id = c.region_id
AND r.region_name = 'Europe')