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