我没有太多的子查询练习,并且编写此查询时非常困难。我基本上需要做的是从user_info
表中选择符合以下条件的所有记录。
user_info
和otherTable
包含与两个表相关的user_id
字段。如果user_info
变量等于$state
和ot.state
,我需要从ot.user_id = ui.user_id
中选择所有字段,同时仍保留user_info
WHERE语句的所有条件。< / p>
SELECT * FROM users_info ui
WHERE cond1=1 AND cond2=2 AND (ot.state = $state AND ui.user_id = ot.user_id)
(
SELECT * FROM otherTable as ot
WHERE ui.user_id = ot.user_id
)
注意我相信我对我的查询很谨慎, 我很感激有关如何实现这一目标的任何澄清。
非常感谢提前!
答案 0 :(得分:2)
听起来我只需要将两张桌子连在一起并应用其余的约束:
select
from
users_info ui
inner join otherTable ot
on ui.user_id = ot.user_id
where
cond1=1 AND
cond2=2
AND ot.state = $state
如果您想使用子查询:
select
from
users_info ui
inner join (select user_id from otherTable where state = $state) ot
on ui.user_id = ot.user_id
where
cond1=1 AND
cond2=2
或者您可以改为使用where子句:
select
from
users_info ui
where
cond1=1 AND
cond2=2 and
ui.user_id in (select user_id from otherTable where state = $state)