mysql主表链接2字段到同一个表

时间:2011-12-24 09:48:46

标签: mysql

我有一个主表'activitynot'它有2个字段链接到samtable'成员'。

如何从成员表中获取名称,下面的代码为member.Sname提供正确的名称,但

(SELECT member.Sname
FROM activitynote
INNER JOIN member
ON activitynote.idmemberref = member.idmember limit 1 )

它为每一行提供相同的名称正确

SELECT member.Sname, activitynote.idactivity, (SELECT member.Sname
FROM activitynote
INNER JOIN member
ON activitynote.idmemberref = member.idmember limit 1 )

FROM activitynote
INNER JOIN member
ON activitynote.idactivity = member.idmember

1 个答案:

答案 0 :(得分:1)

您需要将其设为相关子查询:

SELECT member.Sname
     , activitynote.idactivity
     , ( SELECT member.Sname
         FROM member                       --- JOIN removed
         WHERE activitynote.idmemberref = member.idmember 
         LIMIT 1 
       ) AS member2_name
FROM activitynote
  INNER JOIN member
    ON activitynote.idactivity = member.idmember

或两次加入member表:

SELECT member.Sname
     , activitynote.idactivity
     , member2.Sname AS member2_name
FROM activitynote
  INNER JOIN member
    ON activitynote.idactivity = member.idmember
  LEFT JOIN member AS member2
    ON activitynote.idmemberref = member2.idmember