按最大日期分组3个表

时间:2017-08-17 09:45:58

标签: mysql join max

客户可以进行多次查询,查询可以进行多次更新。我试图查看每个查询和最新更新。我能够提取最新日期,但不能提取与之相关的更新。我已经看到了类似于我的答案,但他们似乎只处理了一次加入,我不明白如何使用这些来找到解决方案。

这是我的sql

select c.name, i.inquirycontent, u.updatecontent, max(u.date) from inquiries i
inner join customers c on c.customerid = i.customerid
left join updates u on u.inquiryid = i.inquiryid
group by i.inquiryid

即使我省略了客户表,我仍然无法将最新更新与其内容相匹配。我怎么能这样做?

编辑 - 根据要求,这里有一些示例数据

+------------+------+
| customerid | name |
+------------+------+
| 1          | jeff |
+------------+------+
| 2          | anne |
+------------+------+

+-----------+-----------------+------------+
| inquiryid | inquirycontent  | customerid |
+-----------+-----------------+------------+
| 1         | inquiry1content | 1          |
+-----------+-----------------+------------+
| 2         | inquiry2content | 1          |
+-----------+-----------------+------------+
| 3         | inquiry3content | 2          |
+-----------+-----------------+------------+

+----------+-----------------+-----------+----------+
| updateid | updatecontent   | inquiryid | date     |
+----------+-----------------+-----------+----------+
| 1        | update1content  | 1         | 01-01-17 |
+----------+-----------------+-----------+----------+
| 2        | update2content  | 1         | 03-01-17 |
+----------+-----------------+-----------+----------+
| 3        | update3content  | 3         | 04-01-17 |
+----------+-----------------+-----------+----------+

这就是我想要查询输出的内容 -

+------+-----------------+----------------+----------+
| name | inquirycontent  | latestupdate   | date     |
+------+-----------------+----------------+----------+
| jeff | inquiry1content | update2content | 03-01-17 |
+------+-----------------+----------------+----------+
| jeff | inquiry2content | NULL           | NULL     |
+------+-----------------+----------------+----------+
| anne | inquiry3content | update3content | 04-01-17 |
+------+-----------------+----------------+----------+

1 个答案:

答案 0 :(得分:0)

这是使用UNION的原始解决方案,但它可以满足我的需要。第一个选择按其最新更新查找所有唯一查询,第二个选择查找尚未更新的所有行。

(select c.name, i.inquirycontent, u.updatecontent, t2.mxdate
from updates u
inner join inquiries i on i.inquiryid = u.inquiryid
inner join customers c on c.customerid = i.customerid
inner join
(
  select max(u.date) mxdate, i.inquiryid
  from updates u
  left join inquiries i on i.inquiryid = u.inquiryid
  group by i.inquiryid
) t2
  on u.inquiryid = t2.inquiryid
  and u.date = t2.mxdate)
UNION
(select c.name, i.inquirycontent, u.updatecontent, u.date 
from inquiries i
left join updates u on u.inquiryid = i.inquiryid
inner join customers c on c.customerid = i.customerid
where u.updatecontent is NULL)