MySQL查询建议

时间:2013-05-02 06:49:09

标签: mysql sql

我有一个像这样的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

父母的姓名将附有孩子的姓名,如姓氏。

2 个答案:

答案 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