我正在尝试为Postgresql编写一个sql查询,该查询查看主题的描述表和另一个表,该表记录了描述中附加了多少喜欢或不喜欢或其他标志。我希望它通过计数表,找到附加到每个描述的所有标志,找到每个描述有多少相同标志的总和,然后按照每个标志的数量排序减去有多少不喜欢它等等,然后返回所有描述的列表,按照前面描述的等式的总和(喜欢 - 不喜欢等)和喜欢,不喜欢等的数量排序。这是我到目前为止的代码的例子(有更多的变量在喜欢/不喜欢变量部分):
SELECT likes, dislikes, positive - negative AS orderCondition
FROM( SELECT d.id, d.l_id, d.user_id, d.description, a.flaggee_id,
SUM( CASE WHEN a.actions_id = 1 THEN 1 WHEN actions_id = 6 THEN 1 ELSE 0 END ) AS positive,
SUM( CASE WHEN a.actions_id <> 1 THEN 1 WHEN a.actions_id <> 6 THEN 1 ELSE 0 END ) AS negative,
SUM( CASE WHEN a.actions_id = 1 THEN 1 ELSE 0 END ) AS likes,
SUM( CASE WHEN a.actions_id = 2 THEN 1 ELSE 0 END ) AS dislikes
FROM descriptions d, description_actions a
WHERE d.id = a.flaggee_id OR d.id > 0 AND d.id <> a.flaggee_id
GROUP BY d.id, a.flaggee_id ) as result
ORDER BY orderCondition DESC;
但这不起作用,它返回一个没有错误的空集。表中的数据是随机的,用于测试,id是整数,不是id的东西是随机字符串,当单独查询表时结果是准确的,所以不是数据的情况不是在表格中。我很难搞清楚......任何帮助都会受到赞赏。
答案 0 :(得分:0)
我想通了,我需要指定它是左连接,为了在标志表为空时仍然显示结果,我还在外部选择中添加了变量。这是工作查询
SELECT description, likes, dislikes, positive - negative AS orderCondition
FROM( SELECT d.id, d.l_id, d.user_id, d.description AS description, a.flaggee_id,
SUM( CASE WHEN a.actions_id = 1 THEN 1 WHEN actions_id = 6 THEN 1 ELSE 0 END ) AS positive,
SUM( CASE WHEN a.actions_id <> 1 THEN 1 WHEN a.actions_id <> 6 THEN 1 ELSE 0 END ) AS negative,
SUM( CASE WHEN a.actions_id = 1 THEN 1 ELSE 0 END ) AS likes,
SUM( CASE WHEN a.actions_id = 2 THEN 1 ELSE 0 END ) AS dislikes
FROM descriptions d LEFT JOIN description_actions a ON a.flaggee_id = d.id
GROUP BY d.id, a.flaggee_id ) as result
ORDER BY orderCondition DESC;