2016-06-30 148 views
0

我卡住了一些我無法弄清楚如何解決它。有3個表格位置,模型,User_Likes。我想在一些國家和國家的城市裏獲得最受歡迎的模特。左加入子查詢返回null

表位置

​​

臺模型

Model_ID, Phone, Loc_ID 

表User_Likes

Model_ID, User_ID, Date 

實施例的數據:

位置:

1 | NULL | USA  | usa 
2 | NULL | Germany | germany 
3 | 1 | New York | new-york 
4 | NULL | Rusia | rusia 

型號:

Seda | 11 | 1 
Zelda | 33 | 2 
Dilara | 22 | 3 

User_Likes

Seda | 1 | 0 
Seda | 2 | 0 
Zelda | 1 | 0 
Dilara | 1 | 0 

我的查詢

SELECT U.Model_ID, M.Loc_ID, M.Name, M.Top_ID, M.Perma, COUNT(*) FROM User_Likes as U 
    LEFT JOIN (SELECT Model.ID, Model.Loc_ID, Yer.Name, Yer.Top_ID, Yer.Perma From Model 
     LEFT JOIN (SELECT Locations.Loc_ID, Locations.Name, Locations.Top_ID, Locations.Perma FROM Locations WHERE Locations.Loc_ID = ? OR Locations.Top_ID = ?) as Yer ON Model.Loc_ID = Yer.Loc_ID) 
     as M ON M.ID = U.Model_ID 
GROUP BY U.Model_ID 

結果:

? = 1 

Seda | 1 | USA   | NULL | usa | 2 
Zelde | 3 | New York | 1  | new-york | 2 

這部分是好的,但問題就開始在這裏

? = 4 
Seda | 1 | NULL  | NULL | NULL | 2 
Zelde | 3 | NULL | NULL  | NULL | 2 

結果在這裏需要空

感謝,

回答

1

試試這個查詢,你不需要這些內選擇查詢

SELECT U.Model_ID, 
M.Loc_ID, 
M.Name, 
M.Top_ID, 
M.Perma, 
COUNT(*) FROM User_Likes as U 
    LEFT JOIN Model M ON M.ID = U.Model_ID 
     LEFT JOIN Locations L ON M.Loc_ID = L.Loc_ID WHERE L.Loc_ID = ? OR L.Ust_ID = ? GROUP BY U.Model_ID 
+0

請檢查並讓我知道 –

+0

這個查詢有太多問題,例如沒有L別名或M –

+0

其小錯字請現在檢查 –