如果我不知道正确的术语,我很抱歉,但我们走了:
我有一个包含以下列和行的表:
------------------------------
| id | parent_id | type |
------------------------------
| 1 | 0 | text1 |
| 2 | 1 | text2 |
------------------------------
现在我想要的是选择类型,但如果parent_id
不是0
我希望类型是它的父类+ [它自己的类型]的类型的内容。
因此,在这种情况下,select的输出将是:
----------------
| type |
----------------
| text1 |
| text1[text2] |
----------------
我用concat和if语句尝试这个,但是无法解决这个问题。
你可以帮帮我吗?答案 0 :(得分: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。