id + ...

问题描述 投票:0回答:1
You had it almost right, you must use MAX to get the highest date of a GROUP BY

idtickets ticket_contents我有一个MySQL数据库(在一些服务器上也以MariaDB的形式工作),有2个主表。一个是

Tickets
+----+---------+-------------+
|id  + subject | Create date |
+----+---------+-------------+
|1   | Ticket1 | 2020-05-24  |
+----+---------+-------------+
|2   | Ticket2 | 2020-05-25  |
+----+---------+-------------+
Ticket Contents
+----+-----------+---------------------+-------------+
|id  + ticket_id | update date_time    | content     |
+----+-----------+---------------------+-------------+
|1   | 1         | 2020-05-24 08:30:15 | msg1        |
+----+-----------+---------------------+-------------+
|1   | 2         | 2020-05-25 10:05:15 | msg2        |
+----+-----------+---------------------+-------------+
|1   | 1         | 2020-05-25 12:15:00 | msg3        |
+----+-----------+---------------------+-------------+

而另一个是

+----------+----------+---------------------+
|ticket_id |subject   |last_update          |
+----------+---_------+---------------------+
|1         | Ticket1  | 2020-05-25 12:15:00 |
+----------+----------+---------------------+
|2         | Ticket2  | 2020-05-25 10:05:15 |
+----------+----------+---------------------+

如下所示。

SELECT t.id, c.date_time FROM tickets t JOIN 
   (SELECT ticket_id, date_time FROM tickets_contents GROUP BY ticket_id) c on t.id = c.ticket_id 
group by t.id order by date_time desc 

我需要的是票据列表中的最新内容记录时间和整个票据的最新更新顺序。

这是我写的代码,但它没有提供正确的最新子记录信息。
mysql select group-by mariadb max
1个回答
0
投票

SELECT t.id,t.subject,t2.maxtime
FROM Tickets t 
INNER JOIN (SELECT MAX(`update date_time`) maxtime,ticket_id FROM `Ticket Contents` GROUP BY ticket_id) t2
ON t.id = t2.ticket_id
我有一个MySQL数据库(在一些服务器上也作为MariaDB工作),有2个主表。一个是门票,另一个是 ticket_contents,如下所示。  
© www.soinside.com 2019 - 2024. All rights reserved.