【发布时间】:2017-07-28 12:45:25
【问题描述】:
DB 的示例输入
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 用户的例外输出
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,但例外输出2
【问题讨论】: