我讨厌我不得不问,但我无法处理它。
我有这张表votes
:
type=1
是一个upvote,type=0
将是一个downvote
我想要这个输出:
[
{'video': 'best-of-mehrwert', 'upvote': 2, 'downvote': 0},
{...}
]
我正在使用medoo:
<?php
$votes = $database->query(
// 'SELECT COUNT(video) as votes, video FROM votes GROUP BY video, type'
'
SELECT video,COUNT(*) as counts
FROM votes
GROUP BY video,type;
'
)->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($votes);
给了我
[{"video":"anlaesse","counts":"1"},{"video":"best-of-mehrwert","counts":"2"}]
如何“添加列”,如“upvotes”,即type = 1且type = 0的条目?
答案 0 :(得分:2)
两种变体:
select
video,
sum(case when type=1 then 1 else 0 end) as upvote,
sum(case when type=0 then 1 else 0 end) as downvote
from votes
group by video
和
select
video,
sum(type) as upvote,
sum(1-type) as downvote
from votes
group by video
答案 1 :(得分:1)
我认为,对于您的条件匹配的每一行,SUM
最多为1可能是最简单的:
SELECT
video,
SUM(CASE type WHEN 1 THEN 1 ELSE 0 END) as upvotes,
SUM(CASE type WHEN 0 THEN 1 ELSE 0 END) as downvotes
FROM
votes
GROUP BY
video;
注意,您应该忽略type
中的GROUP BY
,以便为每个视频获得一行。
答案 2 :(得分:0)
您可以使用case
表达式仅计算您感兴趣的投票类型:
SELECT video,
COUNT(CASE type WHEN 1 THEN 1 END) as upvotes
COUNT(CASE type WHEN 0 THEN 1 END) as downvotes
FROM votes
GROUP BY video, type;