Mysql Join:获取每个项目的总收藏夹以及每一行

时间:2017-07-28 12:45:25

标签: mysql node.js join

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

2 个答案:

答案 0 :(得分:1)

问题是您正在过滤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

答案 1 :(得分:-1)

由于您正在执行GROUP BY cushbu_art.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 , (select count(*) from cushbu_mark_user_favorites a where a.id=b.id )  as total_fav
    FROM
        cushbu_mark_user_favorites b
    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
`