多个表上的COUNT(*)

时间:2014-01-19 10:58:50

标签: php mysql

我需要计算在线用户数量。我把它放在两个表中,这是第一个表:

 +-------------+-------------+-------------+
 |      id     |     name    |    status   |
 +-------------+-------------+-------------+
 |      1      |     name    |    1        |
 +-------------+-------------+-------------+
 |      2      |     name    |    1        |
 +-------------+-------------+-------------+
 |      3      |     name    |    0        |
 +-------------+-------------+-------------+

第二张表:

 +-------------+-------------+-------------+
 |      id     |    userid   |  friend_id  |
 +-------------+-------------+-------------+
 |      1      |      1      |    2        |
 +-------------+-------------+-------------+
 |      2      |      1      |    2        |
 +-------------+-------------+-------------+
 |      3      |      2      |    3        |
 +-------------+-------------+-------------+

即另一个表中有多少用户user_id = 1以及有多少用户在线。

1 个答案:

答案 0 :(得分:1)

您可以将表连接在一起,然后进行计数。

SELECT COUNT(*)
FROM table1 AS t1 
JOIN table2 AS t2 ON (t1.id = t2.friendID)
WHERE t2.userID = 1