PHP 复杂 MySQL 查询从不同 table 计数

PHP complex MySQL query Counting from different table

我正在 networking/social 网站上工作,我正在尝试为 return 正在访问同一页面的用户创建一个功能。

select table "USERS" 中的用户如何通过对 table "READING" 中的 user_id 进行计数和分组?

数据库结构如下:

用户

正在阅读

应该return编的是这样的数组

user
  - user_id
  - user_name
  - user_first_name
  - ...
user
  - user_id
  - ...

这是我目前的查询

SELECT r.user_id, u.* FROM reading r, users u GROUP BY r.user_id AS count WHERE u.user_id = r.user_id ORDER BY count DESC

例子tables

用户

// user_id // user_name // user_email
-------------------------------------
    123    /   mentos   /  m@gmail.com
-------------------------------------
    321    / freshmaker / f@gmail.com
-------------------------------------
    231    /  hubba     /  h@gmail.com

正在阅读

//    id  //  user_id   //  timestamp
--------------------------------------
      1   /    123      /   201501050420
      2   /    321      /   201501050420

输出示例

-ARRAY
  -user
     - 123
     - mentos
     - m@gmail.com
   -user
     - 321
     - freshmaker
     - f@gmail.com

您在找这样的东西吗?

SELECT u.*
  FROM 
(
  SELECT DISTINCT user_id
    FROM reading
   WHERE update_timestamp >= NOW() - INTERVAL 5 MINUTE -- or any other appropriate time interval
     AND user_id <> 4 -- depending on the logic you might want to exclude the current user itself
) q JOIN users u
    ON q.user_id = u.user_id

这是一个SQLFiddle演示