我有3张桌子
表学生
表老师
表格消息
我希望得到那些与某人联系的人的姓名和名单。通过以下查询,我可以使用他们的注册,但我无法添加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;
答案 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;