我有三个表T1,T2,T3
我想实现类似的目标
Select T1.X,T1.Y,
exists(
( select T2.Z from T2
union
select T3.Z from T3 ) Result where Result.Z=T1.Y
) from T1
SQL给了我syantx,请帮助我如何实现此结果?
T1 Contains
X Y
1 0
1 1
1 2
1 7
T2 Contains
Z
1
2
T3 Contains
3
4
T2和T3的联盟
1 2 3 4
现在检查T1是否包含这些行
OutPut
X Y Contains
1 0 True
1 1 True
1 2 True
1 7 False
答案 0 :(得分:0)
Select T1.X,T1.Y, ( select case when count(*)>0 then 'true' else 'false' end from
( select T2.Z from T2 union select T3.Z from T3 ) Result where Result.Z=T1.Y )
from T1
这将导致:
X Y (No column name)
1 1 0 false
2 1 1 true
3 1 2 true
4 1 7 false
请参见此处:http://rextester.com/XDW34718(SQL服务器)
和这里:http://rextester.com/VXBN87216(MySql)
结果true
和false
实际上是这里的字符串。据我所知,实际的布尔值通常用1
和0
表示。并且exists
仅作为where
子句的一部分。
或者,您可以使用两个count(*)
之和,例如
SQL Server:http://rextester.com/GBKNRJ77523
Select x,y,
CAST ((select count(*) from t2 where z=y)
+(select count(*) from t3 where z=y) as bit) [Contains]
from T1
MySQL:http://rextester.com/AWOKZ51875
Select x,y,
(select count(*) from t2 where z=y)
+(select count(*) from t3 where z=y)>0 `Contains`
from T1
答案 1 :(得分:0)
我建议使用带有两个case
子句的exists
表达式:
Select t2.X, t1.Y,
(case when exists (select 1 from t2 where t2.z = t1.y then 1
when exists (select 1 from t3 where t3.z = t1.y then 1
else 0
end) as matches
from t1;
请注意,exists
在子查询中比count(*)
好,因为它更快。首先,它可以轻松利用索引(t2(z)
和t3(z)
)。其次,它可以在第一场比赛时停止。