我有会谈表和talk_items表。
Talk有一个is_performed,created_at和family_id字段。
Talk_item具有created_at字段。
(两者都有更多字段,但可以忽略此问题)
谈话可以有talk_items,也可以没有。
我需要先按is_performed字段对对话进行排序(应首先进行未执行的对话),然后按talk_item的最新日期(如果存在)(如果没有)按对话本身的创建日期进行排序。
我有这个查询:
SELECT talks.*,
IFNULL(talk_items.created_at, talks.created_at) AS
sorting_date
FROM `talks`
LEFT JOIN talk_items
ON talk_items.talk_id = talks.id
WHERE talks.family_id = 35536
ORDER BY talks.is_performed ASC,
sorting_date DESC
但是,如果一个对话包含多个talk_item,则此查询为我提供多个对话。
如何获得DISTINCT对话和该对话的最新talk_item的日期(talk_item的ID可用于该对话)?
数据库ID MYSQL。
谢谢。
最佳答案
不添加
group by talks.id
解决这个?
否则是这样的:
SELECT talks.*,
IFNULL(talk_items.created_at, talks.created_at) AS
sorting_date
FROM `talks`
LEFT JOIN
(SELECT * FROM talk_items group by talk_id) as items
ON items.talk_id = talks.id
WHERE talks.family_id = 35536
ORDER BY talks.is_performed ASC,
sorting_date DESC