如何连接两个表,其中一个表中的一列引用其他表中的3列?

时间:2011-12-05 15:23:44

标签: mysql sql join

我有两个表作为User和User_activity,它们的结构是,

用户

id 
name
email
etc..

user_activity

id,
initiator_id,
source_id,
target_id,
activity_code,
activity

这里我想为用户选择所有活动列表(我可以将它们引用到source_id),其中包含启动器,源,目标的所有名称。

如何获得?

3 个答案:

答案 0 :(得分:4)

你只需加入三次,每次使用别名为你引用用户的三次...

SELECT
  user_activity.*,
  Initiator.Name   AS InitiatorName,
  Source.Name      AS SourceName,
  Target.Name      AS TargetName
FROM
  user_activity
INNER JOIN
  user             AS Initiator
    ON Initiator.ID = user_activity.initiator_id
INNER JOIN
  user             AS Source
    ON Source.ID    = user_activity.source_id
INNER JOIN
  user             AS Target
    ON Target.ID    = user_activity.target_id

答案 1 :(得分:0)

SELECT sourceUser.name, targetUser.name, initiatorUser.name FROM user_activity
INNER JOIN User as sourceUser on sourceUser.id = user_activity.source_id
INNER JOIN User as targetUser on targetUser.id = user_activity.target_id
INNER JOIN User as initiatorUser on initiatorUser.id = user_activity.initiator_id
WHERE source_id = MyUserIdQueryValue

答案 2 :(得分:0)

SELECT DT1.*, U.name
  FROM (
        SELECT source_id, activity_code, activity
          FROM user_activity
        UNION 
        SELECT target_id AS source_id, activity_code, activity
          FROM user_activity
        UNION 
        SELECT inititator_id AS source_id, activity_code, activity
          FROM user_activity
       ) DT1
       JOIN User U ON DT1.source_id = U.id;