连接2个表并使用其中一个的最大值进行排序

时间:2014-10-23 13:06:03

标签: mysql

我有会话表和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。

THX。

1 个答案:

答案 0 :(得分:0)

没有添加

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