MySQL查询两次相同的列

时间:2012-06-14 21:47:49

标签: mysql sql

我有两个表ID和NAME

表1

ID | NAME
1  | first
2  | second
3  | third

以及包含ID和PARENT ID

的XREF表

表2

ID | PARENT ID
1  | 0
2  | 1
3  | 2

我想像这样两次检索NAME:NAME |父母姓名

如果可以深入三个级别,但是使用相同的2列表:

结果表

NAME   | PARENT NAME
first  | NULL or EMPTY or this line the not showing at all
second | first
third  | second

...然后我也想弄明白。

2 个答案:

答案 0 :(得分:1)

select t1.Name, t12.Name from
table1 t1 
inner join table2 t2 on t1.ID = t2.ID 
inner join table1 t12 on t2.ParentID = t12.ID

这只会返回2行。如果你想拥有第一行(ID = 1),你只需要outer join

答案 1 :(得分:1)

考虑将parentid作为自引用关系放在第一个表中,而不是为它设置单独的表。

例:

<强>表1

ID  |  PARENTID  |  NAME
---------------------------
1      NULL         first
2      1            second
3      2            third

这样你只需要自己加入表而不是通过第3个表。 (但是假设table1中的行只能有一个父级,而你的设计允许一行一次有多个父级

但是对于你的表结构,这将起作用:

SELECT
    a.name,
    c.name AS 'PARENT NAME'
FROM
    table1 a
LEFT JOIN
    table2 b ON a.id = b.id
LEFT JOIN
    table1 c ON b.parentid = c.id

但是如果你在引用id的同一个表中创建了parentid,那么SQL将被简化为:

SELECT
    a.name,
    b.name AS 'PARENT NAME'
FROM
    table1 a
LEFT JOIN
    table2 b ON a.parentid = b.id