2013-10-02 229 views
0

民間與兩個表連接mysql查詢

我有2個表國家代碼,cctonumbers如下所述。

我有我試過的查詢,但沒有得到所需的輸出。

我的輸出

country   destination      country_code destination_code 

Afghanistan Afghanistan Mobile Etisalat    93  78 
Afghanistan Afghanistan Mobile Etisalat    93  72 
Afghanistan Afghanistan Mobile Roshan    93  79 
Afghanistan Afghanistan        93  93 

希望的輸出

country   destination      country_code destination_code 

Afghanistan Afghanistan Mobile Etisalat    93   78 

Afghanistan Afghanistan Mobile Etisalat    93   72  

Afghanistan Afghanistan Mobile Roshan    93   79 

中使用的表是如下

countrycodes表

id  parentid countryname 
1031  0   afghanistan 
1035  1031  Afghanistan Mobile Etisalat 
1036  1031  Afghanistan Mobile Roshan 

cctonumbers表

id  countrycode_id  parentid   number 
15731 1031    0    93 
15197 1035    15731   78 
15198 1035    15731   72 
15199 1036    15731   79 

該讀音字被使用如下,但沒有得到所希望的結果的查詢。

select * 
    from 
     cctonumbers 
     LEFT JOIN countrycodes as CC 
      ON cctonumbers.countrycode_id = CC.id 
    WHERE 
     ( CC.parentid=0 
     AND number like '93%' 
     and cctonumbers.id in 
       (select cctonumbers.parentid 
        from cctonumbers 
         LEFT JOIN countrycodes as CC 
          ON cctonumbers.countrycode_id = CC.id 
         WHERE number like '7%' 
          AND CC.parentid!=0) 
       ) 
      or ( CC.parentid != 0 
       AND number like '7%' 
       AND CC.parentid in 
         (select CC.id 
          from cctonumbers 
           LEFT JOIN countrycodes as CC 
            ON cctonumbers.countrycode_id=CC.id 
          WHERE CC.parentid=0 
           AND number like '93%') 
      ) 
    ORDER BY 
     cctonumbers.number Asc 
+0

你能說清楚你試圖得到什麼結果嗎? –

+0

我認爲你正在嘗試按順序排列它們? – Kuzgun

回答

0

你似乎在尋找的是與特定國家代碼相關的所有目的地。既然你實際上沒有顯示你的cctonumbers.id = 15731的任何返回結果,我認爲你正在旋轉以獲得你的結果。讓我們倒轉樹,而不是走下去。

只從那些具有父級ID的CCToNumbers記錄開始,因爲它顯示爲只有一級。一旦你有這些子級別的條目,回到其父母的CCToNumbers ...然後分別進入國家代碼表。

SELECT 
     CtoN.ID, 
     PCountry.CountryName, 
     DCountry.CountryName as Destination, 
     CtoNParent.Number as Country_Code, 
     CtoN.Number as Destination_Code 
    from 
     cctonumbers CtoN 
     JOIN cctonumbers as CtoNParent 
      ON CtoN.parentid = CtoNParent.ID 
      AND CtoNParent.number like '93%' 
      JOIN countrycodes as PCountry 
       ON CtoNParent.CountryCode_Id = PCountry.ID 
     JOIN countrycodes as DCountry 
      ON CtoN.CountryCode_Id = DCountry.ID 
    where 
     CtoN.number like '7%'