2013-04-11 67 views
2

對不起選擇具有數據輸出,如果我不知道正確的術語,但在這裏我們去:MySQL的變化來自其他行

我有一個表與下面的列和行:

------------------------------ 
| id | parent_id | type | 
------------------------------ 
| 1  | 0   | text1 | 
| 2  | 1   | text2 | 
------------------------------ 

現在,我要的是選擇類型,但如果parent_id不爲0 我想要的類型爲類型的內容從它的父+本身的類型。

所以輸出的選擇會在這種情況下是:

---------------- 
| type   | 
---------------- 
| text1  | 
| text1[text2] | 
---------------- 

我用CONCAT和if語句嘗試這一點,但無法弄清楚這一點。

你能幫助我嗎?

+0

將這個僅是爲眼前的父母,或你想包括最終的祖先? (後者在MySQL中有問題。) – 2013-04-11 09:42:58

回答

4

嘗試:

select c.id, 
     case c.parent_id 
      when 0 then c.type 
      else concat(p.type,'[',c.type,']') 
     end as type 
from mytable c 
left join mytable p on c.parent_id = p.id 

SQLFiddle here

+0

不應該是'case parent_id'那裏? – 2013-04-11 09:39:20

+1

@MateiMihai:是的 - 現在已經修好了。 – 2013-04-11 09:41:14

+0

非常感謝! 現在你可以在這裏做一個地方嗎?或者這是不可能的,因爲那裏的if語句? – BonifatiusK 2013-04-11 09:49:53

相關問題