我在编写将多个列连接起来并在其上添加另一个选择的SQL语句时遇到麻烦。
我有:
TableA | TableB | TableC
idA | idB | idC
state | idA | idB
| created_time|
我想查找state = CLOSED并且created_time是最新的所有行。
所以我设法编写了这两个查询:
SELECT TableA, TableB, TableC
FROM TableB
JOIN TableA ON TableB.idA = TableA.id
JOIN TableC ON TableB.id = TableC.idB
WHERE TableA.state = 'CLOSED';
另一个查询,该查询应该找到最新的日期:
SELECT t.id, t.created_time, t.idA
FROM TableB t
INNER JOIN
(SELECT id, idA, MAX(created_time) AS MaxDate
FROM TableB
GROUP BY id) tm ON t.id = tm.id AND t.created_time = tm.MaxDate
但是我不知道如何连接这些查询并使它们成为SET(state =“ OPEN”)。
有人可以帮忙吗?
答案 0 :(得分:2)
我认为DISTINCT ON
是您想要的:
SELECT DISTINCT ON (a.id) . . .
FROM TableA a JOIN
TableB b
ON b.idA = a.id JOIN
TableC c
ON b.id = c.idB
WHERE a.state = 'CLOSED'
ORDER BY a.id