票证条目:
id | ticket_status_id
1 | 2
2 | 3
3 | 4
4 | 3
操作日志:
id | ticket_entry_id | action_type | createtime
1 | 1 | 2 | 2022-10-13 15:25:25.202417+00
2 | 1 | 3 | 2022-10-11 11:25:25.202417+00
3 | 2 | 3 | 2022-10-12 12:25:25.202417+00
4 | 3 | 1 | 2022-10-14 15:25:25.202417+00
5 | 4 | 3 | 2022-10-15 15:25:25.202417+00
我希望按其action_type为3的operate_log的create_time值对(3,4)ticket_entry中的所有ticket_status_id进行排序,而ticket_status_id不在(3,4)中或action_type不为3的operate_log的那些ticket_entry将保留在结果的最后
预期结果应该是
id | action_type
4 | 3
2 | 3
1 | 2
3 | 4
我试过这个
SELECT DISTINCT
( e.* ), o.create_time
FROM
ticket_entries e
LEFT JOIN operate_logs o ON e.ID = o.ticket_entry_id
AND o.action_type = 3
ORDER BY
CASE
WHEN e.ticket_status_id IN ( 3, 4 ) THEN
1
END,
o.create_time ASC NULLS LAST
结果表明
ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 10: CASE
但这句话很管用
SELECT DISTINCT
(e.*), o.create_time
FROM
ticket_entries e
LEFT JOIN operate_logs o ON e.ID = o.ticket_entry_id
AND o.action_type = 3
ORDER BY
o.create_time ASC NULLS LAST
ticket_entries和operate_logs之间关系是一对多
如果我想让sql正常工作,我还应该选择什么
1条答案
按热度按时间0g0grzrc1#
使用case表达式,首先获取状态为3和4以及操作为3的行,然后将其他行排在最后。然后按create_time对这两个数据集进行排序。