gpt4 book ai didi

Mysql加入:get total favourites for each item along with each row

转载 作者:行者123 更新时间:2023-11-29 18:35:09 27 4
gpt4 key购买 nike

我的数据库的示例输入

1)cushbu_users

id first_name last_name email 
1 sh s sh@sh.com
2 sb s sh1@sh.com

2)cushbu_art

   id user_id title   image_name 
1 1 cool cool.jpeg
2 2 funny funny.jpeg
3 1 blaaa blaa.jpeg
4 2 foo foo.jpeg

3)cushbu_mark_user_favorites-存储收藏的项目的详细信息

 id user_id art_id
1 1 1
2 1 2
3 2 1
4 2 2

As you see two users Favorited two arts so the total count
for favourite of each art is `two`

我想获得每个用户最喜欢的艺术作品的总收藏数

我的 id=1 用户的异常(exception)输出

art_id artist_name total_fav
1 sh s 2
2 sb s 2

这是对此的查询

    SELECT
cushbu_art.id AS art_id,
cushbu_art.title,
cushbu_art.image_name,
CONCAT(
cushbu_users.first_name,
' ',
cushbu_users.last_name
) AS artist_name , count(cushbu_mark_user_favorites.id) as total_fav
FROM
cushbu_mark_user_favorites
LEFT JOIN cushbu_art ON cushbu_art.id=cushbu_mark_user_favorites.art_id
LEFT JOIN cushbu_users ON cushbu_users.id = cushbu_art.artist_id
WHERE cushbu_mark_user_favorites.user_id=1
GROUP BY cushbu_art.id

但它返回

art_id artist_name total_fav
1 sh s 1
2 sb s 1

每行仅返回 total_fav 1,但异常(exception)输出 2

最佳答案

问题在于您正在过滤 WHERE cushbu_mark_user_favorites.user_id=1,因此无法从其他用户那里获取收藏夹的数量。这个想法是第二次加入表,但没有这个限制。推测,未经测试...

SELECT
cushbu_art.id AS art_id,
cushbu_art.title,
cushbu_art.image_name,
CONCAT(
cushbu_users.first_name,
' ',
cushbu_users.last_name
) AS artist_name , b.favorites_count as total_fav
FROM
cushbu_mark_user_favorites
LEFT JOIN cushbu_art ON cushbu_art.id=cushbu_mark_user_favorites.art_id
LEFT JOIN cushbu_users ON cushbu_users.id = cushbu_art.artist_id
LEFT JOIN (SELECT art_id,count(*) as favorites_count FROM cushbu_mark_user_favorites GROUP BY art_id) as b ON b.art_id=cushbu_art.id
WHERE cushbu_mark_user_favorites.user_id=1
GROUP BY cushbu_art.id

关于Mysql加入:get total favourites for each item along with each row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45373911/

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