我收到此错误,查询在SQLite中有效。
ActiveRecord::StatementInvalid (PG::GroupingError: ERROR: COLUMN "receipts.is_read" must appear IN the GROUP BY clause OR be used IN an aggregate FUNCTION
不确定该怎么做,当我移除合并部件时也会发生这种情况。我不知道还有什么我可以指定它来使它工作。有什么想法吗?
SELECT DISTINCT conversations.id, COALESCE(CASE WHEN receipts.is_read = 't' THEN 't' END, 'f') AS READ, conversations.updated_at, p1.nickname, p2.nickname
FROM conversations
INNER JOIN notifications ON notifications.conversation_id = conversations.id
INNER JOIN receipts ON receipts.notification_id = notifications.id
INNER JOIN profiles p1 ON p1.id = notifications.sender_id
INNER JOIN profiles p2 ON p2.id = receipts.receiver_id
WHERE (receipts.receiver_id = #{SELF.id} ) AND notifications.sender_id != #{SELF.id} OR (notifications.sender_id = #{SELF.id}) AND receipts.receiver_id != #{SELF.id}
GROUP BY conversations.id
ORDER BY conversations.updated_at DESC
答案 0 :(得分:1)
您的DISTINCT
和GROUP BY
以及一些未分组的列混合在一起。
在用DISTINCT ON
(以及其他一些清理工具)替换这些混乱之后,这可行,但它不清楚,你真正想要实现的目标:
SELECT DISTINCT ON (c.id)
c.id, COALESCE(r.is_read, FALSE) AS read
, c.updated_at, p1.nickname AS nickname1, p2.nickname AS nickname2
FROM conversations c
JOIN notifications n USING (conversation_id)
JOIN receipts r USING (notification_id)
JOIN profiles p1 ON p1.id = n.sender_id
JOIN profiles p2 ON p2.id = r.receiver_id
WHERE (r.receiver_id = #{SELF.id} AND n.sender_id <> #{SELF.id} OR
r.receiver_id <> #{SELF.id} AND n.sender_id = #{SELF.id})
ORDER BY c.id, c.updated_at DESC;
这会让您获得与每个群组中最新conversations.updated_at
共享相同conversations.id
的行。说明:
Select first row in each GROUP BY group?