我有两张这样的表:
表“用户”:
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
并另外COUNT个“用户”拥有此源,但是如果有额外的过滤器(PHP mysqli的请求),则另外对“sources”表进行排序它的用户数量。
这样做的最佳方式是什么,是否可以在一个声明中完成?
--------------添加了编辑----------
第一部分(SELECT with count from count table)我这样做:
SELECT
id, name
(select count(*) from users where source = sources.id) as sourceUsersCount
FROM sources
现在,如何按用户在每个来源中对此列表进行排序?
答案 0 :(得分:0)
如果您需要,请检查以下查询。
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;
答案 1 :(得分:0)
计算用户数:
SELECT sources.*, COUNT(users.user_id) FROM sources
LEFT JOIN users ON users.source_id = sources.source_id
GROUP BY sources.source_id;
我假设过滤器是指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;
您总是可以在末尾添加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;
答案 2 :(得分:0)
通过这样做实现:
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
//\\
这是最好的方式,还是有一些更快的变种?