我的查询如下:
SELECT
id,
CASE
WHEN type IN (2,10) THEN (select dr from s_d where server_id=s.id)
ELSE dr END AS dr
FROM s
WHERE dr in (1,2,3)
两个表中都存在'dr'字段。所以当(1,2)中的'type'字段按s.dr过滤时(需要s_d.dr)。如何使用JOIN进行操作?
table s:
id (int)
type (int)
dr (int)
table s_d:
id (int)
server_id (int)
dr (int)
答案 0 :(得分:0)
select
id,
case
when type in (2,10) then sd.dr
else s.dr
end as dr
from
s
inner join
s_d sd on sd.server_id = s.id
where s.dr in (1,2,3)
答案 1 :(得分:0)
select
id,
case
when type in (2,10) then sd.dr
else s.dr
end as dr
from s
left join s_d sd on sd.server_id = s.id
where s.dr in (1,2,3)
与@Clodoaldo的答案相反,我的解决方案将返回null作为行的dr,其中s_d表中没有对应的行存在于s行中,在@Clodoaldo的解决方案中这些行被过滤掉了。
它取决于您的要求,哪种答案对您的案例是正确的。