2012-10-02 184 views
0

我必須使用count和group,我有點困惑。mysql query select count

我有2個表:

  • 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

現在我想收到的所有行的計數包含它們在同一個ID user_stalking.user_iduser_stalking.user_stalking_id字段。

+0

什麼是用戶跟蹤,聽起來令人毛骨悚然? – allen213

回答

0

首先,我希望在這個聲明之前的某個地方檢查/ sanatizing $ _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

'$ _SESSION'不需要消毒(雖然如果它是從客戶端提供的值中分配的,這樣的值應該是),因爲它只能從應用程序中寫入。 – eggyal

+0

它從不傷害消毒。 – mmiles

0

select count(*)AS count from users u,users_stalking us where u.user_id = us.user_stalking_id?

(對不起,錯字,這是從手機發送)

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 
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