有人可以帮忙解决这个问题吗?
SELECT A.post_id, B.post_id, A.ul_value as "likes", B.ul_value as "dislikes"
FROM wp_like_dislike_counters as A,
wp_like_dislike_counters as B
where
A.post_id = B.post_id
and A.ul_key = 'u_like'
and B.ul_key = 'u_dislike'
我得到的结果:
3, 3, 1, 2
4, 4, 3, 2
我想要的结果:
3, 3, 1, 2
4, 4, 3, 2
1, 1, 0, 1
下面是表格中的数据。请注意,id为32的行的post_id为1,而l_value为1(表示1不喜欢)。由于这个post_id没有" like"的行,我想在上面想要的结果中显示为0。这种表结构可以实现吗?
id | post_id | l_key | l_value
---+---------+-----------+---------
35 | 3 | u_dislike | 2
34 | 4 | u_dislike | 2
31 | 4 | u_like | 3
32 | 1 | u_dislike | 1
36 | 3 | u_like | 1
答案 0 :(得分:4)
您希望使用条件聚合而不是连接来执行此操作:
select post_id,
sum(case when ul_key = 'u_like' then ul_value else 0 end) as likes,
sum(case when ul_key = 'u_dislike' then ul_value else 0 end) as dislikes
from wp_like_dislike_counters
group by post_id;