2017-08-17 63 views
1

客戶可以進行多種查詢,並且查詢可以有許多更新。我正在嘗試查看每個查詢和最新更新。我能夠提取最新的日期,但不能更新與之相關的更新。我看到類似於我的答案,但他們似乎只處理一個連接,我不明白我如何使用這些來找到解決方案。最大日期組3表格

這裏是我的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 | 
+------+-----------------+----------------+----------+ 
+0

請發表您的表的幾行 – RealCheeseLord

+0

如何格式化? –

+0

縮進4個空格,並嘗試使它看起來不錯,如代碼塊 – RealCheeseLord

回答

0

這是使用UNION粗的解決方案,但它工作我需要的。第一個select通過最新更新查找所有唯一查詢,第二個select查找所有尚未更新的行。

(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)