gpt4 book ai didi

MySQL 聚合?

转载 作者:行者123 更新时间:2023-11-29 08:47:20 29 4
gpt4 key购买 nike

我有以下两张表

Table: items
ID | TITLE
249 | One
250 | Two
251 | Three

我投票给这些:

Table: votes
VID | IID | userid | votes
01 | 249 | 6 | 5
02 | 249 | 7 | -5
03 | 249 | 8 | 5
04 | 249 | 9 | 5
05 | 250 | 6 | -5
06 | 250 | 7 | -5
07 | 250 | 8 | 5

-5 表示反对,+5 表示赞成。假设我以用户 6 身份登录,SQL 查询将给我什么:

Table: result
ID | TITLE | TOTALVOTES | UPVOTES | DOWNVOTES | CURRENTUSERVOTED
249 | One | 4 | 3 | 1 | 1
250 | Two | 3 | 1 | 2 | 1
251 | Three | 0 | 0 | 0 | 0

最佳答案

在聚合函数中使用 CASE 表达式:

SELECT    a.ID,
a.TITLE,
COUNT(b.IID) AS TOTALVOTES,
COUNT(CASE WHEN b.votes = 5 THEN 1 END) AS UPVOTES,
COUNT(CASE WHEN b.votes = -5 THEN 1 END) AS DOWNVOTES,
COUNT(CASE WHEN b.userid = 6 THEN 1 END) AS CURRENTUSERVOTED
FROM items a
LEFT JOIN votes b ON a.ID = b.IID
GROUP BY a.ID,
a.TITLE

关于MySQL 聚合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12231103/

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