node.js - Mysql Join:get total favourites for each item along with each row -
sample input 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-store details of favourited item
id user_id art_id 1 1 1 2 1 2 3 2 1 4 2 2 see 2 users favorited 2 arts total count favourite of each art `two` i want favourited arts of each user total favourite
my excepted output user of id=1
art_id artist_name total_fav 1 sh s 2 2 sb s 2 here query that
select cushbu_art.id art_id, cushbu_art.title, cushbu_art.image_name, concat( cushbu_users.first_name, ' ', cushbu_users.last_name ) artist_name , count(cushbu_mark_user_favorites.id) total_fav 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 cushbu_mark_user_favorites.user_id=1 group cushbu_art.id but returns
art_id artist_name total_fav 1 sh s 1 2 sb s 1 returns total_fav 1 each row excepted output 2
the problem filtering where cushbu_mark_user_favorites.user_id=1 it's not possible number of favorites other users. idea join table second time, without contraints. speculating, untested...
select cushbu_art.id art_id, cushbu_art.title, cushbu_art.image_name, concat( cushbu_users.first_name, ' ', cushbu_users.last_name ) artist_name , b.favorites_count total_fav 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(*) favorites_count cushbu_mark_user_favorites group art_id) b on b.art_id=cushbu_art.id cushbu_mark_user_favorites.user_id=1 group cushbu_art.id
Comments
Post a Comment