使用第一个查询中的值执行第二个查询

时间:2019-11-13 11:45:42

标签: sql postgresql

我的第一个查询返回thread_id,其中is_root = true

SELECT thread_id 
FROM messages 
WHERE recipient_id = '331e1bce-2f71-4187-8ce2-edcc615de55b`
AND is_root = true

如何在每个返回的thread_id上使用JOIN来获取最新消息?

我的第二个查询获取最新消息

SELECT * FROM messages WHERE thread_id = '1b290bac-e694-40c4-86b6-c5b6e09ae8c3'
ORDER BY date_posted DESC LIMIT 1

我尝试使用子查询,但这给了我这个错误:

WITH rootcomments as(
    SELECT thread_id 
    FROM messages 
    WHERE recipient_id = '331e1bce-2f71-4187-8ce2-edcc615de55b'
    AND is_root = true
), latestmessages as(
    SELECT * FROM messages WHERE thread_id = rootcomments.thread_id
    ORDER BY date_posted DESC LIMIT 1
)SELECT * FROM latestmessages
missing FROM-clause entry for table "rootcomments"

我该如何通过联接来做到这一点?

编辑1::_________________________________________________

enter image description here

应该返回message_id 3,因为它具有最高的时间戳记

但它仅返回2

enter image description here

试图将DESC更改为ASC,但没有效果

1 个答案:

答案 0 :(得分:2)

请勿使用function thunk(fn) { let args = [...arguments].slice(1, arguments.length); return function () { return fn.apply(null, args); }; }; function trampoline(thunk) { while (typeof thunk === 'function') { thunk = thunk(); } return thunk; } function isEven(n) { let arg = n; function _isEven() { console.log(); return (arg === 0 ? true : isOdd(arg - 1)); }; return trampoline(thunk(_isEven, n)); } function isOdd(n) { let arg = n; function _isOdd() { return (arg === 0 ? false : isEven(arg - 1)); }; return trampoline(thunk(_isOdd, n)); } 。使用JOIN

DISTINCT ON

SELECT DISTINCT ON (thread_id) m.* FROM messages m WHERE m.recipient_id = '331e1bce-2f71-4187-8ce2-edcc615de55b` AND m.is_root = true ORDER BY thread_id, date_posted DESC; 是便捷的Postgres扩展名。括号中的每个值组合返回一行。特定的行由DISTINCT ON确定。