MySQL的/ SQL。将两个select语句组合在两列中

时间:2017-11-12 13:16:44

标签: mysql sql

我需要SQL查询的帮助。我有两个独立的SELECT查询:

SELECT
     tbl_events.eventName as eventName1
  FROM tbl_events 
  INNER JOIN tbl_users
  ON tbl_events.eventAutorID = tbl_users.userID
  WHERE tbl_users.userID = "6"; 

Output:

eventName1:
eventNametest1
eventNametest2
eventNametest3
eventNametest9

 SELECT
     tbl_events.eventName as eventName2
  FROM tbl_users
  INNER JOIN tbl_participants
  ON tbl_users.userID = tbl_participants.participantUser
  INNER JOIN tbl_events
  ON tbl_participants.participantEvent = tbl_events.eventID
  WHERE tbl_users.userID = "6";  

Output:

eventName2:
eventNametest1
eventNametest3
eventNametest6
eventNametest12
eventNametest15
eventNametest16

第一个查询是选择用户创建的具有特定id(例如id = 6)的所有事件(名称),第二个是获取具有特定id的用户被添加为参与者的所有事件(事件名称)。 如何将这些语句合并为一个,但结果分为两个不同的列? 输出应该如下所示:

   eventName1 | eventName2

  eventNametest1   eventNametest1
  eventNametest2   eventNametest3
  eventNametest3   eventNametest6
  eventNametest9   eventNametest12
  NULL             eventNametest15
  NULL             eventNametest16

2 个答案:

答案 0 :(得分:0)

MySQL不提供FULL JOIN。并且,如果某人可能授权某项活动而不参与,则您需要这样做。

一种方法使用UNION ALL和变量:

SELECT MAX(authName) as authName, MAX(partName) as partName
FROM ((SELECT e.eventName as authName, NULL as partName, (@rne := @rne + 1) as rn
       FROM tbl_events e JOIN
            tbl_users u
            ON e.eventAutorID = u.userID CROSS JOIN
            (SELECT @rna := 0) params
       WHERE u.userID = 6
       ORDER BY eventName
      ) UNION ALL
      (SELECT NULL, e.eventName, (@rnp := @rnp + 1) as rn
       FROM tbl_participants p JOIN
            tbl_events e
            ON e.eventId = p.participantEvent CROSS JOIN
            (SELECT @rnp := 0) params
       WHERE p.participantUser = 6
       ORDER BY e.eventName
      )
     ) ap
GROUP BY rn;

答案 1 :(得分:0)