SQL 复杂选择
SQL complex selection
我必须想出一个非常复杂的选择。
不知道这是怎么可能的,但我认为是这样。
有两个table:
线程:主键是列'thread_id'
订阅:主键是'user'和'thread_id'
我需要一个选择选择所有话题按有多少人订阅了它们。
示例情况:
在 table 'threads'
中有 个 ID 为 1 - 5 的线程
订阅 table 看起来像这样:
user thread_id
x 1
x 2
y 2
z 4
z 2
可以看到,订阅最多的帖子是2个。
我想要一个将 thread_id 2 排在第一位的选择,因为 2 是订阅最多的一个。
所以有人可以帮助我吗?我试了一个小时没找到解决方法
您可以使用计数和分组依据
select user, count(*)
from Subscribe
group by thread_id
order by thread_id;
我认为这是您可能的解决方案
SELECT
s.thread_id, COUNT(DISTINCT s.user) AS total_subscribed
FROM
subscribes s
INNER JOIN threads t
ON s.thread_id = t.thread_id
GROUP BY
s.thread_id
ORDER BY
total_subscribed DESC
如果线程中没有重复用户,则不需要 DISTINCT
SELECT thread_id, COUNT(*) AS cpt FROM subscribes GROUP BY thread_id ORDER BY cpt
只需在 thread_id 字段上分组并相应地获得您的计数。虽然不会考虑同一用户的多个绑定,但如果在此 table.
上允许,那将是一个约束问题
select thread_id, count(*) as thread_count from threads group by thread_id, order by thread_count desc;
我必须想出一个非常复杂的选择。 不知道这是怎么可能的,但我认为是这样。
有两个table:
线程:主键是列'thread_id'
订阅:主键是'user'和'thread_id'
我需要一个选择选择所有话题按有多少人订阅了它们。
示例情况:
在 table 'threads'
中有 个 ID 为 1 - 5 的线程订阅 table 看起来像这样:
user thread_id
x 1
x 2
y 2
z 4
z 2
可以看到,订阅最多的帖子是2个。 我想要一个将 thread_id 2 排在第一位的选择,因为 2 是订阅最多的一个。
所以有人可以帮助我吗?我试了一个小时没找到解决方法
您可以使用计数和分组依据
select user, count(*)
from Subscribe
group by thread_id
order by thread_id;
我认为这是您可能的解决方案
SELECT
s.thread_id, COUNT(DISTINCT s.user) AS total_subscribed
FROM
subscribes s
INNER JOIN threads t
ON s.thread_id = t.thread_id
GROUP BY
s.thread_id
ORDER BY
total_subscribed DESC
如果线程中没有重复用户,则不需要 DISTINCT
SELECT thread_id, COUNT(*) AS cpt FROM subscribes GROUP BY thread_id ORDER BY cpt
只需在 thread_id 字段上分组并相应地获得您的计数。虽然不会考虑同一用户的多个绑定,但如果在此 table.
上允许,那将是一个约束问题select thread_id, count(*) as thread_count from threads group by thread_id, order by thread_count desc;