如何在单个查询中正确连接三个MYSQL表?

时间:2018-04-19 22:01:49

标签: mysql

我正在尝试从多个表中获取信息,并且关注者数量的总和不按预期方式运行。我应该看到16跟随,我看到256.此外,在所有用户之间的数据库中只记录了40个“跟随”。

$ SQLTable_UserMeta是一个键/对表,其中单个用户可以有多行,这就是我在查询中有单独连接的原因。

SELECT $SQLTable_Users.`user_id`, $SQLTable_Users.`username`, $SQLTable_Users.`user_lastonline`, $SQLTable_Users.`user_registered`, $SQLTable_Users.`user_status`, SUM($SQLTable_Follows.`following`) AS follows, first_name.`value` AS FirstName, last_name.`value` AS LastName FROM $SQLTable_Users
LEFT JOIN $SQLTable_UserMeta first_name
    ON first_name.`user_id` = $SQLTable_Users.`user_id` AND first_name.`key` = 'first_name'
LEFT JOIN $SQLTable_UserMeta last_name
    ON last_name.`user_id` = $SQLTable_Users.`user_id` AND last_name.`key` = 'last_name'
LEFT JOIN $SQLTable_Follows
    ON $SQLTable_Follows.`follower_user_id` = $SQLTable_Users.`user_id`
GROUP BY $SQLTable_Users.`user_id`
ORDER BY `user_lastonline` DESC LIMIT 100

1 个答案:

答案 0 :(得分:1)

如果您使用$ SQLTable_Follows表来获取关注者的数量,请使用子查询

SELECT $SQLTable_Users.`user_id`, $SQLTable_Users.`username`, $SQLTable_Users.`user_lastonline`, 
$SQLTable_Users.`user_registered`, $SQLTable_Users.`user_status`, 
(SELECT count(*) FROM SQLTable_Follows WHERE SQLTable_Follows.`follower_user_id` =  $SQLTable_Users.`user_id`) AS follows, 
first_name.`value` AS FirstName, last_name.`value` AS LastName FROM $SQLTable_Users
LEFT JOIN $SQLTable_UserMeta first_name
    ON first_name.`user_id` = $SQLTable_Users.`user_id` AND first_name.`key` = 'first_name'
LEFT JOIN $SQLTable_UserMeta last_name
    ON last_name.`user_id` = $SQLTable_Users.`user_id` AND last_name.`key` = 'last_name'
GROUP BY $SQLTable_Users.`user_id`
ORDER BY `user_lastonline` DESC LIMIT 100