从第二个表中通过外键从第一个表中获取字段

时间:2011-03-03 09:55:52

标签: mysql

两个表:类别及其多对多关系:

categories
id | name
1    first
2    second
3    third

relations
parent | child
1        2
1        3

我怎样才能得到这个结果?:

first | second
first | third

我只能

SELECT c.name, r.child 
FROM categories AS c 
LEFT JOIN relations AS r ON c.id = r.parent

结果是

first | 2
first | 3

那么,如何在此表中获取子名称?

2 个答案:

答案 0 :(得分:2)

SELECT c1.name, c2.name
FROM relations AS r
LEFT JOIN categories AS c1 ON r.parent = c1.id
LEFT JOIN categories AS c2 ON r.child = c2.id
WHERE c1.id = 1

答案 1 :(得分:0)

选择categories表两次。

select parent_c.name parent, child_c.name child
from categories parent_c, categories child_c, relations r
where r.parent = parent_c.id and r.child = child_c.id