简体   繁体   中英

mysql, php, how to get a count of users?

i have a table like this:

user  | session
test1 | 11
test1 | 11
test1 | 11
test1 | 21
test1 | 21
test2 | 2
test2 | 2
test3 | 3
test3 | 3
test3 | 32
test3 | 32

i would like to get back that user 1 has 2 sessions , user 2 has 1 sessions , user 3 has 2 sessions bassically how many the same sessions a user has?

i've tryed $sql4 = SELECT user, session , count(*) FROM table group by user, session

and i get the distinct sessions but not the count

any ideas? thanks

edit:

if i use SELECT user, count(*) FROM users GROUP BY user i get test 1 = 5 . it give's me the total nr or sessions instead of total nr of sessions that are the same. in this case 2

SELECT user, count(DISTINCT session) FROM users GROUP BY user

DISTINCT仅用于计算唯一会话

If you want to know the overall number of person online you just need to count the number of user regardless of the session

$sql4 = SELECT COUNT(*) from (
        SELECT  distinct(user)
        FROM table) as innerquery

This will group all by user what ever the session. The result will be a simple integer.

If you need to count the amount of session of each user and do not want to have a count for each session you need to remove the duplicate with a Distinct keyword.

$sql4 = SELECT user, count(distinct(session)) 
        FROM table 
        GROUP by user

The result will be a list of user-># of session

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