0

私はサブクエリをあまり練習したことがなく、このクエリを書くのに非常に苦労しています。基本的に行う必要があるのはuser_info、次の基準に一致するテーブルからすべてのレコードを選択することです。

user_info2 つのテーブルを関連付けるフィールドがotherTable含まれています。WHERE ステートメントのすべての条件を維持しながら、変数がAND に等しい場合は、user_idすべてのフィールドを選択する必要があります。user_info$stateot.stateot.user_id = ui.user_iduser_info

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
)

これを達成する方法についての明確化に感謝します。

よろしくお願いします!

4

1 に答える 1

2

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) 
于 2013-10-28T18:11:02.897 に答える