mysql查询选择计数

时间:2012-10-02 13:06:40

标签: php mysql

我必须使用计数和小组,我有点困惑。

我有两张桌子:

  • users

    id_user | firstname | lastname | genre | logo_src

  • user_stalking

    user_id | user_stalking_id

目前,我的查询如下:

SELECT   us.user_id, us.user_stalking_id, us.notification_viewed, u.id_user,
         u.firstname, u.lastname, u.logo_src, u.genre, us.id, us.date
FROM     users u, user_stalking us
WHERE    us.user_id = ".$_SESSION['user']['id_user']."
     AND us.notification_viewed = 0
     AND us.user_stalking_id = u.id_user
ORDER BY us.date DESC

然后它返回:

John | Jonson | image1.png | male

现在,我希望在user_stalking.user_iduser_stalking.user_stalking_id字段中收到包含相同ID的所有行的计数。

4 个答案:

答案 0 :(得分:0)

首先,我希望在此声明之前的某个地方,您正在检查/审核$ _SEESION ['user'] ['id_user']值,否则您将对注射攻击保持开放态度。

要回答您的问题,您可以通过更改查询来检索这两个值(可能不是最有效的查询)。

SELECT  us.user_id, us.user_stalking_id, us.notification_viewed, u.id_user, u.firstname, u.lastname, u.logo_src, u.genre, us.id, us.date, 
    (SELECT COUNT(s.user_id) FROM user_stalking s WHERE s.user_id = u.user_id) AS stalking_count, 
    (SELECT COUNT(s2.user_id) FROM user_stalking s2 WHERE s2.user_stalking_id = u.user_id) AS being_stalked_count 
FROM    users u, user_stalking us 
WHERE   us.user_id = ".$_SESSION['user']['id_user']." 
    AND us.notification_viewed = 0 
    AND us.user_stalking_id = u.id_user ORDER BY us.date DESC

答案 1 :(得分:0)

从用户u,users_stalking us中选择count(*)AS计数u.user_id = us.user_stalking_id ??

(抱歉打字错误,这是通过电话发送的)

答案 2 :(得分:0)

SELECT   COUNT(us.user_id)
FROM     users AS u
JOIN     user_stalking AS us ON (us.user_stalking_id = u.id_user)
WHERE    us.user_id = ".(int)$_SESSION['user']['id_user']."
          AND us.notification_viewed = 0
GROUP BY us.user_id
ORDER BY us.date DESC

答案 3 :(得分:0)

“现在我想在user_stalking.user_id和user_stalking.user_stalking_id字段中收到包含相同ID的所有行的计数。”

我猜你要找的是一个equi join / inner join查询。

    select count(*) from users u, user_stalking us where us.user_id = ".$_SESSION['user']['id_user']."
 AND u.id_user=us.user_stalking_id