不能将左连接与联合组合

时间:2014-07-12 11:56:07

标签: mysql sql join

我有3张桌子

表学生

  • 名称
  • REGID

表老师

  • 名称
  • REGID

表格消息

  • ID
  • MSG
  • senderid
  • receiverid
  • TS

我希望得到那些与某人联系的人的姓名和名单。通过以下查询,我可以使用他们的注册,但我无法添加left join,因为我一直收到错误:

(SELECT sender_id AS contact FROM messages WHERE receiver_id = '...')

UNION

(SELECT receiver_id AS contact FROM messages WHERE sender_id = '...')

这就是我要为开始做的事情:

SELECT teachers.name,
       teachers.regid
FROM   teachers
       LEFT JOIN ((SELECT sender_id AS contact
                   FROM   messages
                   WHERE  receiver_id = '...')
                  UNION DISTINCT
                  (SELECT receiver_id AS contact
                   FROM   messages
                   WHERE  sender_id = '...')) 
         ON t.contact = teachers.regid; 

2 个答案:

答案 0 :(得分:1)

您可以在left join子句中添加from

SELECT . . .
FROM ((SELECT sender_id AS contact FROM messages WHERE receiver_id = '...')
      UNION
      (SELECT receiver_id AS contact FROM messages WHERE sender_id = '...')
     ) LEFT JOIN
     blah
     ON . . . ;

这是你在做什么?

答案 1 :(得分:1)

您错过了已加入的内部查询的别名。 此外,要拥有明确的查询联合,您应该只使用UNION运算符:

SELECT teachers.name, teachers.regid 
FROM teachers 
LEFT JOIN ( (SELECT sender_id AS contact 
             FROM   messages 
             WHERE  receiver_id = '...') 
             UNION 
            (SELECT receiver_id AS contact 
             FROM   messages 
             WHERE  sender_id = '...') ) t -- here!
ON t.contact = teachers.regid;