简体   繁体   中英

mysql query select count

I must use count and group and I'm a little confused.

I have 2 tables:

  • users

     id_user |  firstname |  lastname |  genre |  logo_src  

and

  • user_stalking

     user_id |  user_stalking_id  

At the moment, my query looks like:

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

and it returns:

John | Jonson | image1.png | male

Now I want to receive count of all rows that contains them same ID in the user_stalking.user_id and user_stalking.user_stalking_id fields.

First off, I hope somewhere before this statement you are checking/sanatizing the $_SEESION['user']['id_user'] value or else you are leaving yourself wide open to injection attacks.

To answer your question, you can retrieve both those values by altering the query like so (may not be the most efficient query).

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

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

( sorry for typo, this is sent from phone)

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

"Now I want to receive count of all rows that contains them same ID in the user_stalking.user_id and user_stalking.user_stalking_id fields."

I guess what you are looking for is an equi join/inner join query.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM