我有一个像这样的MySQL表 -
ID NAME PARENT
=====================
1 Class 0
2 Math 1
3 Physics 1
4 Cooking 0
5 Italian 4
6 Chinese 4
我想要一个能给我输出的查询 -
ID NAME
=====================
1 Class
2 Math Class
3 Physics Class
4 Cooking
5 Italian Cooking
6 Chinese Cooking
父母的姓名将附有孩子的姓名,如姓氏。
答案 0 :(得分:2)
LEFT JOIN
,因为PARENT
上的ID
不匹配。
SELECT a.ID,
CONCAT(a.Name, ' ', COALESCE(b.name,'')) Name
FROM TableName a
LEFT JOIN TableName b
ON a.Parent = b.ID
您也可以使用CONCAT_WS()
,以便省略COALESCE()
SELECT a.ID,
CONCAT_WS(' ', a.Name, b.name) Name
FROM TableName a
LEFT JOIN TableName b
ON a.Parent = b.ID
答案 1 :(得分:0)
SELECT t1.ID, CONCAT(t1.NAME, ' ', t2.NAME) AS NAME
FROM your_table t1
INNER JOIN your_table t2 ON t1.PARENT = t2.ID