2012-10-10 197 views
0

我試着做一個查詢,看起來像這樣:SQL IN子查詢

SELECT `online`.user_id, users.profile_image_url, profile_info.profile_text, users.kind_of_relationship, users.gender_search, users.country 
FROM `online`, users, profile_info 
WHERE (`online`.user_id = users.id) 
AND (`online`.user_id = profile_info.profile_user_id) 
AND (users.user_age >= '25' AND users.user_age <= '38') 
AND (users.kind_of_relationship = 'Friendship') 
AND (users.gender = 'female') 
AND users.country IN (SELECT searching_countries.country FROM searching_countries, `online` WHERE `online`.user_id = searching_countries.user_id); 

和失敗。

但是如果我運行此查詢這樣

SELECT `online`.user_id, users.profile_image_url, profile_info.profile_text, users.kind_of_relationship, users.gender_search, users.country 
FROM `online`, users, profile_info 
WHERE (`online`.user_id = users.id) 
AND (`online`.user_id = profile_info.profile_user_id) 
AND (users.user_age >= '25' AND users.user_age <= '38') 
AND (users.kind_of_relationship = 'Friendship') 
AND (users.gender = 'female') 
AND users.country IN ('Sweden', 'Austria'); 

那麼查詢工作正常。

另外,如果我只是運行查詢:

SELECT searching_countries.country FROM searching_countries, `online` WHERE `online`.user_id = searching_countries.user_id 

即時得到結果瑞典,奧地利..

任何想法,爲什麼這IN(SELECT searching_countries.country FROM searching_countries,online WHERE online .user_id = searching_countries.user_id)不想工作?

預先感謝您!

+1

你是什麼意思用'失敗'?查詢不會返回確切的結果?或者它有語法錯誤? –

+0

嗨, 它顯示NULL。那就是問題 – Mensur

回答

0
UNION SELECT `online`.user_id, users.profile_image_url, profile_info.profile_text, users.kind_of_relationship, users.gender_search, users.country FROM `online`, users, profile_info WHERE (`online`.user_id = users.id) AND (`online`.user_id = profile_info.profile_user_id) AND (users.user_age >= '25' AND users.user_age <= '38') AND (users.kind_of_relationship = 'Friendship') AND (users.gender = 'female') AND users.country IN ('Sweden', 'Austria'); 
0

在子查詢中添加ALIASonline表。

SELECT ... 
FROM... 
WHERE.... 
...AND (users.gender = 'female') 
AND users.country IN 
(
SELECT searching_countries.country 
FROM searching_countries, `online` x 
WHERE x.user_id = searching_countries.user_id 
) 
+0

這一個returs也Null =( – Mensur

0

我認爲這樣做的伎倆,現在是我的解決方案。

很抱歉,如果出現了任何missunderstanding但我還是想通過做在分享我如何解決我的問題。事情不需要是,有時complecated :)

SELECT `online`.user_id, users.user_name, users.profile_image_url, profile_info.profile_text, users.kind_of_relationship, users.gender_search, users.country 
FROM `online`, users, profile_info 
WHERE (`online`.user_id = users.id) 
AND (`online`.user_id = profile_info.profile_user_id) 
AND (users.user_age >= '25' AND users.user_age <= '38') 
AND (users.kind_of_relationship = 'Friendship') 
AND (users.gender = 'female') 
AND users.country IN (SELECT country FROM searching_countries WHERE user_id ='55');