2017-04-17 31 views
2
I want all country name in result along with those whose sel_id is 1 

使用其中condion上選擇的結果我有2代表國表和price_plan_detail如何在MySQL

country table 
    Id name 
    1 India 
    2 china 
    3 bangladesh 
    4 china 

price_plan_detail 
id country_id_fk name  sel_id 
1 1   india 1 1 
2 1   india 2 1 
3 1   india 3 2 
4 1   china 1 2 
5 2   china 1 1 
6 2   china 2 2 

我希望所有從國表裏國家和衍生具SEL price_plan_detail表中的所有匹配的記錄id爲1.

india India 1  1 
india India 2  1 
china china 1  1 
india null  NULL 
india Null  Null 
china null  null 
bangladesh NULL NULL 
shrilanka NULL NULL 

我想要這個結果。

這是我的查詢

SELECT * from (select c.name,p.name as p,p.sel_id as sel_id from country as c LEFT join price_plan_detail as p ON p.`country`=c.id) as t WHERE t.sel_id=1 

與此查詢我得到錯誤的結果

name p sel_id 
india India 1  1 
india India 2  1 
china china 1  1 

這是我的結果是錯在這裏我想所有sel_id 1 我希望所有國家的國家結果中的名稱以及那些其sel_id爲1的結果

+0

您能否快速提供DML和DDL或創建SQLFiddle.com?我相信很容易。我可以解決它。 –

+0

你有什麼第4列? –

+0

請說明您的具體問題或添加額外的細節,以確切地突出你需要什麼。正如目前所寫,很難確切地說出你在問什麼。請參閱[問]頁面以獲得澄清此問題的幫助。 –

回答

1

您需要將sel_id=1篩選條件從where子句加入連接條件,因爲在連接表後應用了where子句。

select c.name,p.name as pname,p.sel_id as sel_id 
from country as c 
LEFT join price_plan_detail as p 
    ON p.`country`=c.id and p.sel_id=1 
+0

它工作正常..偉大的工作 – vaibhav