0

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

第一个表 'friends' 有 userID、friendID 和 status

第二个表 'users' 有 firstName、lastName、userID

第三个表 'users_temp' 有 tempUserID、tempUserName

我希望有一个查询从用户 ID 或朋友 ID = 1 的“朋友”中全部提取,并将另一个字段(如果用户 ID = 1,则获取朋友 ID,或者如果朋友 ​​ID = 1,则获取用户 ID)加入“用户”/“用户临时”其中 userID = users.userID 并离开 join users_temp 如果存在。

现在我有这个,但它一直返回错误的结果。它返回的用户 ID 也必须是唯一的,所以我只为每个用户返回 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 设置

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

任何帮助将非常感激!

谢谢,

韦斯

4

1 回答 1

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 列吗?或者其他会做吗?

于 2013-03-04T00:50:32.390 回答