这里我有桌子
1)users_interests
user_id interest_id
677 12
677 14
677 13
2)answer_points
user_id in_id point
677 12 -1
677 12 1
677 12 1
677 14 1
678 14 1
3)兴趣
id name
12 movie
13 cooking
14 music
这里我想做的是,我想要这样的输出
interest_id name point
12 movie 1
13 cooking 0
14 music 1
user_id=677
我试过了这个查询
select ui.interest_id,i.name,sum(a.answer_points) as total from
users_interests as ui inner join interests as i on i.id=ui.interest_id
left join answer_points as a on a.in_id=ui.interest_id
where i.user_id='677' group by a.in_id
但不计算1
投票。它为电影
3 total
答案 0 :(得分:1)
试试这个
select id,name,coalesce(find_in_set(id,in_id),0) as points
from interests i
left join(select distinct in_id
from answer_points a where point = 1)a
on a.in_id = i.id cross join users_interest u
where u.user_id = 677 group by id;
答案 1 :(得分:1)
此代码适用于您的要求,另请查看以下链接
http://rextester.com/NQXE66482
SELECT
J.interest_id AS 'ID',
I.NAME AS 'NAME',
CASE WHEN K.TOTAL != 0 THEN K.TOTAL
ELSE 0 END AS 'Total'
FROM
users_interests AS J
JOIN
interests AS I
ON
J.interest_id = I.id
LEFT JOIN
(SELECT
a.id AS 'ID',
a.name AS 'NAME',
SUM(b.point) as 'TOTAL'
FROM
interests a
LEFT JOIN
answer_points b
ON a.id = b.in_id
WHERE user_id = 677
GROUP BY 1) AS K
ON
J.interest_id = K.id
WHERE
J.user_id = 677
GROUP BY 1
ORDER BY 1
答案 2 :(得分:0)
您应该使用左连接开始兴趣
select i.id, sum(a.point)
from interests as i
left users_interests as ui on ui.interest_id = i.id
left join answer_points as a on a.user_id = ui.user_id and a.in_id = i.interest_id
where i.user_id=677
group by a.id
答案 3 :(得分:0)
我只需像这样改变JOIN
,
select ui.interest_id, i.name, COALESCE(SUM(a.answer_points),0) as total from users_interests as ui
join interests as i on i.id = ui.interest_id
left join answer_points as a on a.in_id = ui.interest_id AND a.user_id = ui.user_id
where ui.user_id='677'
group by a.in_id
我必须在user_id
中对join
进行比较AND a.user_id = ui.user_id