我说5张桌子,
user , t1, t2, t3, t4
user
有一个名为id
的字段。
t1
到t4
都有一个名为user_id
的相应字段和一个名为verification
的字段。
现在,我需要明确(或唯一地)从user
中选择user table
id
,t1
至少在t4
到{{{{}}中的一个表中至少存在一次verification
1}},以及true
字段为{{1}}的位置。
答案 0 :(得分:3)
从您的详细说明中可以看出您已接近解决方案。需要使用EXISTS和OR(假设TRUE替换为1):
SELECT id FROM User u WHERE
EXISTS(SELECT 1 FROM t1 WHERE u.id = t1.user_id AND t1.verification =1)
OR EXISTS(SELECT 1 FROM t2 WHERE u.id = t2.user_id AND t2.verification =1 )
OR EXISTS(SELECT 1 FROM t3 WHERE u.id = t3.user_id AND t3.verification =1 )
OR EXISTS(SELECT 1 FROM t4 WHERE u.id = t4.user_id AND t4.verification =1 )
答案 1 :(得分:1)
乏味而不是困难:
SELECT id FROM User JOIN t1 ON user.id = t1.user_id WHERE verification = TRUE
UNION
SELECT id FROM User JOIN t2 ON user.id = t2.user_id WHERE verification = TRUE
UNION
SELECT id FROM User JOIN t3 ON user.id = t3.user_id WHERE verification = TRUE
UNION
SELECT id FROM User JOIN t4 ON user.id = t4.user_id WHERE verification = TRUE
答案 2 :(得分:0)
我会在t1
- t4
表格中使用UNION
set来获取user_id
,并将该结果用于IN()
clause user
表,如下所示:
SELECT * FROM user
WHERE id IN (SELECT user_id FROM t1 WHERE verification = TRUE
UNION
SELECT user_id FROM t2 WHERE verification = TRUE
UNION
SELECT user_id FROM t3 WHERE verification = TRUE
UNION
SELECT user_id FROM t4 WHERE verification = TRUE)'
就IN()
的工作原理而言,您还可以获得不同的user
表格结果。
答案 3 :(得分:0)
试试这个:
select
distinct u.user
from
user u
where
exists (
(select user_id from t1 where t1.user_id = u.id and t1.verification = true)
OR (select user_id from t2 where t2.user_id = u.id and t2.verification = true)
OR (select user_id from t3 where t3.user_id = u.id and t3.verification = true)
OR (select user_id from t4 where t4.user_id = u.id and t4.verification = true)
)