2013-10-28 58 views
0

我還沒有太多的子查詢練習,並且在編寫此查詢時遇到了極其困難的時間。我基本上需要做的是從user_info表中選擇符合以下條件的所有記錄。子查詢作爲WHERE語句中的條件

user_infootherTable包含與兩個表相關的user_id字段。如果$state變量等於ot.stateot.user_id = ui.user_id,同時仍保持WHERE語句的所有條件,我需要從user_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 
) 

注意我相信我wayyy了與我的查詢, 我明白如何做到這一點任何澄清。

非常感謝提前!

+0

您應該準備語句和綁定變量而不是注入變量進入你的SQL。 – h2ooooooo

回答

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) 
+0

謝謝安德魯。然而,這是一個問題,b/c查詢是動態創建的,並且select語句已經連接了兩個表,到了上面的查詢時,這就是爲什麼我想知道我是否可以創建一個子查詢,查詢類型的東西,所以我不必深入研究創建'select'語句的所有條件? – AnchovyLegend

+0

不確定我關注,但看到我上面添加的查詢。 – Andrew