我想打印一个人的最后一条消息,但是每人只能打印他的最新消息。我使用PostgreSQL 10。
+-----------+----------+--------------+
| name | body | created_at |
+-----------+----------+--------------+
| Maria | Test3 | 2017-07-07 |
| Paul | Test5 | 2017-06-01 |
+-----------+----------+--------------+
我已经在下面的SQL查询中进行了尝试,这确实使我感到很遗憾,但是不幸的是,人们的人数翻了一番。
SELECT * FROM messages WHERE receive = 't' GROUP BY name ORDER BY MAX(created_at) DESC
+-----------+----------+--------------+ | name | body | created_at | +-----------+----------+--------------+ | Maria | Test1 | 2016-06-01 | | Maria | Test2 | 2016-11-01 | | Maria | Test3 | 2017-07-07 | | Paul | Test4 | 2017-01-01 | | Paul | Test5 | 2017-06-01 | +-----------+----------+--------------+
我试图用DISTINCT删除重复项,但不幸的是,我收到此错误消息:
SELECT DISTINCT ON (name) * FROM messages WHERE receive = 't' GROUP BY name ORDER BY MAX(created_at) DESC
ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON (name) * FROM messages ^ : SELECT DISTINCT ON (name) * FROM messages WHERE receive = 't' GROUP BY name ORDER BY MAX(created_at) DESC
您有任何想法我该如何解决?
我想打印一个人的最后一条消息,但是每人只能打印他的最新消息。我使用PostgreSQL10。+ ----------- + ---------- + -------------- + |名称|身体| ...
使用DISTINCT ON
,但右ORDER BY
:
您将按以下方式使用DISTINCT ON
: