我有以下表格:
scenes
------
scene_id
title
video_url
modified_at
uuid
likes
----
scene_id
uuid
active
users
-----
uuid
username
问题1: 我想按降序获得场景,scene_id,作者的喜欢数量;请注意,我们需要统计那些在喜欢的表格中活跃的喜欢!
我的尝试:
SELECT s.scene_id,s.video_url,s.title,s.uuid, u.username as author,s.data,count(l.active) as likes
FROM scenes s
left join likes l
on l.scene_id = s.scene_id
join users u
on u.uuid = s.uuid
where s.video_url IS not NULL
group by s.scene_id
order by modified_at DESC;
但这是在计算所有喜欢的东西,无论它是否活跃!我不知道如何在我的查询中添加那个!
问题2:
另外我想知道是否可以在结果集中添加另一个列来显示特定用户(uuid可以传递并在where子句中使用)是否喜欢结果集中的每个场景?是否可以只在一个查询中生成此结果?
如果您需要更多说明,请与我们联系!
谢谢!
答案 0 :(得分:1)
在active
列上添加谓词很简单;它只取决于它所代表的......是一个整数类型的列,使用0和/或NULL表示它"非活动",以及1和/或任何正整数表示它是active
?
为了获得场景,scene_id,作者的喜欢数量降序",您可以这样做:
SELECT COUNT(l.scene_id) AS cnt_likes
, s.scene_id AS scene_id
, a.username AS author
FROM scenes s
LEFT
JOIN users a
ON a.uuid = s.uuid
LEFT
JOIN likes l
ON l.scene_id = s.scene_id
AND l.active+0
GROUP BY s.scene_id
ORDER BY cnt_likes DESC, s.scene_id DESC, a.username DESC
如果列active
是字符类型,并且您使用的值是"是"为了表明喜欢是活跃的,你需要改变谓词,
替换:
AND l.active+0
使用:
AND l.active = 'yes'
等
对于第二个问题,确定拥有“活跃喜欢”的用户'对于一个场景
(即聚合中包含的行),这是有问题的,因为可能有多个用户对场景有类似的看法...我们确定哪些用户返回,只是其中任何一个,所有这些?...我只是更仔细地重新阅读你的问题。您想知道一个特定的已识别用户是否具有该场景的like
。
只测试同一行上的uuid是否等于你要查找的值,然后返回0或1,然后得到MAX()。
e.g。
SELECT COUNT(l.scene_id) AS cnt_likes
, s.scene_id AS scene_id
, a.username AS author
, MAX(l.uuid = 'auser') AS liked_by_user
FROM scenes s
LEFT
JOIN users a
ON a.uuid = s.uuid
LEFT
JOIN likes l
ON l.scene_id = s.scene_id
AND l.active+0
GROUP BY s.scene_id
ORDER BY cnt_likes DESC, s.scene_id DESC, a.username DESC
<强>后续强>
表达式
MAX(l.uuid = 11 )
可以返回1,0或NULL。 (1相当于boolean TRUE,0相当于boolean false,NULL是未知的,或者在这种情况下,我们将它视为FALSE。
在MySQL中,整数可以被视为布尔值,而布尔值则被视为整数。
返回字符串&#39; true&#39;或者&#39; false&#39;,您可以使用IF()函数
IF(MAX(l.uuid = 11 ), 'true', 'false')