加入MySQL表

时间:2012-06-04 13:22:58

标签: mysql

我有以下表格格式:

成员信息

 mem_id | mem_name
    ------------------
     1         A
     2         B 
     3         C

project_members

fk_mem_id | meb_parent_id
-------------------------
    1          0
    2          1
    3          2

我要求结果如下:

mem_id | child| parent
--------------------------
   1      A     NULL
   2      B      A
   3      C      B

我试过但失败了......任何想法......?

SELECT pm.*, m1.meb_name as child, m2.meb_name as parent 
FROM members m1
LEFT JOIN members m2 
ON m1.meb_parent_id = m2.meb_id

1 个答案:

答案 0 :(得分:0)

SELECT project_members.fk_mem_id, 
       a.mem_name AS child, 
       b.mem_name AS parent 
FROM   project_members 
       INNER JOIN members a 
               ON project_members.fk_mem_id = a.mem_id 
       LEFT JOIN members b 
              ON project_members.meb_parent_id = b.mem_id