[英]MySQL - Combine tables and order by max date
我有两个mysql表,我在下面简化了。 我想创建一个查询,它将从最近的日期提取两个表和订单的数据。 因此,如果notes表中有一个条目(或条目),它将查找该cid的最新notes_date,如果没有条目,则将使用contact_date作为该cid。
contacts
+-----+--------+---------------------+
| cid | name | contact_date |
+-----+------------------------------+
| 1 | george | 2014-03-03 12:24:48 |
| 2 | john | 2014-02-28 15:39:20 |
| 3 | paul | 2014-02-14 10:13:58 |
| 4 | ringo | 2014-02-06 07:13:17 |
+-----+--------+---------------------+
notes
+-----+-----+---------------------+
| nid | cid | notes_date |
+-----+---------------------------+
| 1 | 1 | 2014-03-06 15:43:55 |
| 2 | 1 | 2014-03-14 20:14:12 |
| 3 | 4 | 2014-03-20 22:10:14 |
+-----+-----+---------------------+
这是我想从查询中得到的结果
4 ringo 2014-03-20 22:10:14
1 george 2014-03-14 20:14:12
2 john 2014-02-28 15:39:20
3 paul 2014-02-14 10:13:58
任何帮助将非常感激
这有几个部分。 一个是获取笔记的最新日期。 另一个是将其与contacts
数据相结合,然后选择正确的日期。
以下方法使用聚合子查询和联接来进行计算:
select c.cid, c.name, coalesce(n.notes_date, c.contact_date) as thedate
from contacts c left outer join
(select n.cid, max(notes_date) as notes_date
from notes
group by n.cid
) n
on c.cid = n.cid
你应该使用join。 你可以查询像 -
select cont.cid, cont.name, nots.notes_date from contacts cont inner join notes nots on cont.cid=nots.cid order by nots.notes_date
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.