简体   繁体   English

MySQL,带有COUNT的SELECT,但如果排序则为GROUP BY

[英]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. 现在,我需要从source选择(*)并另外拥有具有此源的COUNT个“用户”,但是如果有其他过滤器(PHP mysqli的请求),则需要按其用户数对“源”表进行排序。

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)我是这样做的:

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: 我认为通过过滤器意味着WHERE子句:

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: 而且,您始终可以在最后附加一个ORDER BY进行排序:

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? 这是最好的方法,还是有一些更快的变体?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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