如何从联接表中获取最新日期

时间:2019-05-25 20:23:58

标签: mysql join

我希望我的表message_mapping按表message_idmessages的最新日期排序(两个表中都message_id)。

如果我尝试在MAX(messages.send_at)语句中使用ORDER BY,它不会更改结果

SELECT * FROM message_mapping 
LEFT JOIN messages ON message_mapping.message_id = messages.message_id
WHERE landlord = 16 OR tenant = 16
GROUP BY message_mapping.message_id
ORDER BY messages.send_at DESC

这是我的桌子的样子:

message_mapping:

+------------+----------+--------+-------------+
| message_id | landlord | tenant | property_id |
+------------+----------+--------+-------------+
| 34         | 194      | 16     | 160         |
+------------+----------+--------+-------------+
| 35         | 194      | 16     | 318         |
+------------+----------+--------+-------------+
| 36         | 194      | 207    | 160         |
+------------+----------+--------+-------------+

消息:

+-----+------------+--------+----------+--------------+----------------+
| id  | message_id | sender | receiver | message_text | send_at        |
+-----+------------+--------+----------+--------------+----------------+
| 256 | 34         | 16     | 194      | lorem ipsum  | 10.05.19 22:37 |
+-----+------------+--------+----------+--------------+----------------+
| 257 | 34         | 194    | 16       | lorem ipsum  | 10.05.19 22:38 |
+-----+------------+--------+----------+--------------+----------------+
| 258 | 34         | 194    | 16       | lorem ipsum  | 20.05.19 22:38 |
+-----+------------+--------+----------+--------------+----------------+
| 259 | 34         | 194    | 16       | lorem ipsum  | 25.05.19 22:38 |
+-----+------------+--------+----------+--------------+----------------+
| 260 | 35         | 16     | 194      | lorem ipsum  | 13.05.19 22:38 |
+-----+------------+--------+----------+--------------+----------------+

send_at列的格式为DATETIME,如下所示:2019-05-13 22:39:00 我不知道为什么是d

我想看到的是表message_mapping(其中发送者或接收者= 16),它是根据表消息中的最新日期排序的。

知道我可以改变什么吗?

2 个答案:

答案 0 :(得分:0)

解决方案是还要在select中的send_at列中选择max()值。这样,订购就很好了。

SELECT message_mapping.*, max(messages.send_at) AS latest_send_at
FROM message_mapping 
LEFT JOIN messages ON message_mapping.message_id = messages.message_id
WHERE landlord = ? OR tenant = ?
GROUP BY message_mapping.message_id
ORDER BY latest_send_at DESC");

答案 1 :(得分:-1)

在选择项中使用max(messages.send_at),而不是按顺序使用订单。

SELECT messages.message_id, max(messages.send_at) 
FROM message_mapping 
LEFT JOIN messages ON message_mapping.message_id 
= messages.message_id
WHERE landlord = 16 OR tenant = 16
GROUP BY message_mapping.message_id