gpt4 book ai didi

php - MySQL,使用 COUNT 进行 SELECT,但如果排序则使用 GROUP BY

转载 作者:行者123 更新时间:2023-11-29 17:48:21 24 4
gpt4 key购买 nike

我有两个这样的表:

表“用户”:

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

表“来源”:

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

现在我需要 SELECT (*) FROM source 并另外计算具有此源的“用户”,但是如果有额外的过滤器(PHP mysqli 的请求),则另外对“源”进行排序“按用户数量排列的表格。

最好的方法是什么?是否可以在一条语句中完成?

--------------添加编辑----------

第一部分(从另一个表中选择计数)我这样做:

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

现在,如何按每个来源中的用户数对该列表进行排序?

最佳答案

如果这是您所需要的,请检查以下查询。

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;

关于php - MySQL,使用 COUNT 进行 SELECT,但如果排序则使用 GROUP BY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49616717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com