MySQL LEFT JOIN无效

时间:2012-02-26 09:33:26

标签: mysql sql left-join

我有一个mysql连接,并且由于某些原因它返回了image和firstname和lastname的重复字段。就像它没有正确加入一样。

这是SQL

SELECT a.follow_id, a.user_id, a.following, b.firstname, b.lastname, c.firstname,   c.lastname, b.image, c.image
FROM followers a 
LEFT JOIN candidates b ON a.following = b.user_id
LEFT JOIN donors c On a.following = c.user_id
WHERE a.user_id = 222
LIMIT 9

候选人和捐赠者都有名字和姓氏和图像,所以我需要获取这些字段,但不能复制字段。

我的结果 enter image description here

有人可以告诉我我做错了吗?

提前致谢。

2 个答案:

答案 0 :(得分:1)

SELECT a.follow_id, a.user_id, a.following, b.firstname, b.lastname, b.image
FROM followers a 
LEFT JOIN candidates b ON a.following = b.user_id
WHERE a.user_id = 222


UNION DISTINCT


SELECT a.follow_id, a.user_id, a.following, c.firstname,   c.lastname,  c.image
FROM followers a 
LEFT JOIN donors c On a.following = c.user_id
WHERE a.user_id = 222

我不确定我是否理解你的问题。

答案 1 :(得分:-1)

您的follow_idfollowing字段是唯一的。由于您使用唯一的以下字段加入候选者和捐赠者表,因此您需要创建2个子查询,从每个表中提取相关信息,并从关注者表中提取user_id。

然后,您可以从关注者表到每个子查询进行连接:

SELECT f.user_id,
       can.firstname,
       can.lastname,
       don.firstname,
       don.lastname,
       can.image,
       don.image
FROM   followers f
       LEFT JOIN (SELECT a.user_id,
                         a.following,
                         b.firstname,
                         b.lastname,
                         b.image
                  FROM   followers a
                         INNER JOIN candidates b
                           ON a.following = b.user_id) can
         ON f.user_id = can.user_id
       LEFT JOIN (SELECT a.user_id,
                         a.following,
                         c.firstname,
                         c.lastname,
                         c.image
                  FROM   followers a
                         INNER JOIN donors c
                           ON a.following = c.user_id) don
         ON f.user_id = don.user_id
WHERE  f.user_id = 222
LIMIT  9;