如何从 2 SQL 表中提取出现次数

How to pull the count of occurences from 2 SQL tables

我在我创建的 SQlite3 数据库上使用 python。我创建了数据库,目前只是使用命令行来尝试使 sql 语句正确。

我有 2 个 table。

Table 1 - users
user_id, name, message_count

Table 2 - messages
id, date, message, user_id

当我设置 table 两个时,我在创建消息时添加了这条语句 table,但我不知道它是做什么的:

FOREIGN KEY (user_id) REFERENCES users (user_id)

我想要做的是 return 一个包含 2020 年期间姓名和消息计数的列表。我使用此语句获取了 2020 年的帖子总数,并且有效:

SELECT COUNT(*) FROM messages WHERE substr(date,1,4)='2020';

但我正在努力弄清楚我是否应该加入 table,或者是否有办法只提取我需要的信息。我想要的语句看起来像这样:

SELECT name, COUNT(*) FROM users JOIN messages ON messages.user_id = users.user_id WHERE substr(date,1,4)='2020';

一个选项使用相关子查询:

select u.*,
    (
        select count(*) 
        from messages m 
        where m.user_id = u.user_id and m.date >= '2020-01-01' and m.date < '2021-01-01'
    ) as cnt_messages
from users u

此查询将利用 messages(user_id, date) 上的索引。 您也可以 join 并聚合。如果你想允许没有消息的用户,left join 是合适的:

select u.name, count(m.user_id) as cnt_messages
from users u
left join messages m 
    on m.user_id = u.user_id and m.date >= '2020-01-01' and m.date < '2021-01-01'
group by u.user_id, u.name

请注意,根据文字日期过滤 date 列比对其应用函数(排除使用索引)更有效。

您缺少按用户分组的 GROUP BY 子句:

SELECT u.user_id, u.name, COUNT(*) AS counter 
FROM users u JOIN messages m
ON m.user_id = u.user_id 
WHERE substr(m.date,1,4)='2020'
GROUP BY u.user_id, u.name