我的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

最佳答案

问题是您正在过滤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 - Mysql Join:获取每个条目以及每行的总收藏夹,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45373911/

10-12 15:45