带有union的MySQL查询返回错误的结果

时间:2013-03-04 00:31:22

标签: mysql union

我无法找出执行此MySQL语句的最佳方法。

第一个表'friends'具有userID,friendID和status

第二个表'users'具有firstName,lastName,userID

第三个表'users_temp'有tempUserID,tempUserName

我希望有一个查询来自“朋友”,其中userID或friendID = 1并加入另一个字段(如果userID = 1然后获取friendID,或者如果friendID = 1,则获取用户ID)加入“用户”/ 'users_temp',其中userID = users.userID,如果存在,则加入users_temp。

现在我有这个,但它一直在返回错误的结果。它返回的userID也必须是唯一的,所以我只返回每个用户1(因为这是一个朋友列表)

SELECT users.userid, 
       users.fbid              AS fbID, 
       users.firstname         AS firstName, 
       users.lastname          AS lastName, 
       users.phonenumber       AS phoneNumber, 
       users.avatar            AS avatar, 
       users_temp.tempusername AS tempUserName, 
       status, 
       friendid 
FROM   users 
       JOIN (SELECT friendid, 
                    userid, 
                    status 
             FROM   friends 
             WHERE  friendid = $userid 
                    AND ( ( status != 2 ) 
                          AND ( status != 3 ) ) 
             UNION ALL 
             SELECT friendid, 
                    userid, 
                    status 
             FROM   friends 
             WHERE  userid = $userid 
                    AND ( ( status != 2 ) 
                          AND ( status != 3 ) )) foo 
         ON users.userid = foo.userid 
       LEFT JOIN users_temp 
              ON users.userid = users_temp.tempuserid 

我创建了一个sqlfiddle,希望能进一步解释我的sql setup

http://sqlfiddle.com/#!2/690c3/4

非常感谢任何帮助!

谢谢,

韦斯

1 个答案:

答案 0 :(得分:0)

据我所知,问题可能是您在unionall查询的第二部分中使用了不正确的字段进行连接

请尝试以下

SELECT users.userid, 
  users.fbid              AS fbID, 
  users.firstname         AS firstName, 
  users.lastname          AS lastName, 
  users.phonenumber       AS phoneNumber, 
  users.avatar            AS avatar, 
  users_temp.tempusername AS tempUserName, 
  status
FROM   users 
   JOIN (SELECT friendid AS joinid, 
            userid AS otherid, 
            status 
     FROM   friends 
     WHERE  friendid = 1 
            AND ( ( status != 2 ) 
                  AND ( status != 3 ) ) 
     UNION ALL 
     SELECT userid AS joinid, 
            friendid AS otherid, 
            status 
     FROM   friends 
     WHERE  userid = 1 
            AND ( ( status != 2 ) 
                  AND ( status != 3 ) )) foo 
   ON users.userid = foo.otherid 
  LEFT JOIN users_temp 
      ON users.userid = users_temp.tempuserid

编辑:更改了unionall的第二个子查询的列顺序。你真的需要主查询中的friendid列吗?或者其他人会这样做吗?