简体   繁体   中英

MySQL, SELECT with COUNT, but GROUP BY if sort

I have two tables like these:

Table "users":

user_id | source
----------------
      1 | 2
      2 | 2
      3 | 3
      4 | 0

Table "sources":

source_id | name
----------------
        1 | "one"
        2 | "two"
        3 | "three"
        4 | "four"

Now I need to SELECT (*) FROM source and additionally COUNT "users" that have this source, BUT if there is an additional filter(requests by PHP mysqli), then additionally sort "sources" table by its users count.

What is the best way to do so, and is it possible to do in one statement?

--------------Added editing----------

The first part(SELECT with count from another table) I'm doing this way:

SELECT 
    id, name
    (select count(*) from users where source = sources.id) as sourceUsersCount
FROM sources

And now, how to order this list by users count in each source?

Please check the below query if this is what you need.

select s.*,a.c from sources s
left join
 (select count(*) as c,source as src 
   from user u join sources s 
      on s.source_id = u.source group by u.source) a 
on s.source_id = a.src;

Count the number of users:

SELECT sources.*, COUNT(users.user_id) FROM sources
LEFT JOIN users ON users.source_id = sources.source_id
GROUP BY sources.source_id;

I assume by filters you mean the WHERE clause:

SELECT sources.*, COUNT(users.user_id) FROM sources
LEFT JOIN users ON users.source_id = sources.source_id
WHERE sources.source_id = 2
GROUP BY sources.source_id;

And you can always attach an ORDER BY on the end for sorting:

SELECT sources.*, COUNT(users.user_id) FROM sources
LEFT JOIN users ON users.source_id = sources.source_id
GROUP BY sources.source_id
ORDER BY sources.source_id DESC;

Achieved it by doing so:

SELECT 
    sources.*,
    count(users.source) as sourceUsersCount
FROM sources
LEFT JOIN users ON sources.id = users.source
//In case of additional filters
WHERE 
    id != 0 AND (name LIKE %?% OR id LIKE %?%)
//\\
GROUP BY sources.id 
//In case of sorting by "users" count
ORDER BY sourceUsersCount ASC 
//\\

Is it the best way, or maybe there are some faster variants?

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