按时间顺序对联接中的数据进行排序以获取最新条目

时间:2018-09-24 05:41:39

标签: mysql sql join left-join mariadb

我有3个数据库表:

  • OpenROHeader
  • OpenROData
  • OpenRONotes

标题和数据每小时更新一次(覆盖),同时手动添加注释并通过字段“ RO_Number”链接

我想让SQL执行的操作是检索最新的“注释”(按“ date_updated”)

SELECT file_date, rod.id as id, key_id, key_name, key_value, DATE_FORMAT(expected_close_date , '%d/%m/%y' ) as expected_close_date, wty_dept
FROM OpenROHeader roh 
JOIN OpenROData rod ON roh.id=rod.header_id 
LEFT JOIN OpenRONotes ron ON rod.key_value=ron.ro_number 
WHERE roh.customer_id='193' 
GROUP BY key_id, key_name

Notes表中有2个条目-我想要最新的条目:

id, customer_id, ro_number, expected_close_date, advisor_notes, wty_dept, date_updated
4059, 193, 'S117986', NULL, 'WTY_ON<br>- S.W.', 'on', '2018-09-24 05:02:45'
4060, 193, 'S117986', NULL, 'WTY_OFF<br>- S.A.', NULL, '2018-09-24 05:03:24'

我希望它从ID为4060 NOT 4059的行中返回SELECT中的数据(最后2列)

http://sqlfiddle.com/#!9/f00326/1/0

但是不是从2018-09-24 05:03:24返回最新的'wty_dept'(NULL)

我的SQL语句从2018-09-24 05:02:45(旧)返回上一个条目'on'

如何对联接进行排序以返回最新数据

3 个答案:

答案 0 :(得分:0)

我认为您不需要进行排序,只需确保以后没有评论即可。我已经对我们如何查找便笺进行了假设,但是假设我正确无误,这应该为您做到(我以为我理解您的要求后更新!)

SELECT file_date, advisor_notes, rod.id as id, key_id, key_name, key_value, DATE_FORMAT(expected_close_date , '%d/%m/%y' ) as expected_close_date, wty_dept
FROM OpenROHeader roh 
JOIN OpenROData rod ON roh.id=rod.header_id 
LEFT JOIN OpenRONotes ron ON rod.key_value=ron.ro_number 
WHERE roh.customer_id='193' 
and not exists (select * from OpenRONotes ron2 where rod.key_value=ron2.ro_number and ron2.date_updated>ron.date_updated)

答案 1 :(得分:0)

按Clouse分组后放入desc 例如- 从学生的GROUP BY部分desc中选择*; 它会g

答案 2 :(得分:0)

您可以从三个表的联接中获取最新的列:

SELECT file_date, rod_id AS id, key_id, key_name, key_value, DATE_FORMAT(expected_close_date , '%d/%m/%y' ) AS expected_close_date, wty_dept
FROM OpenROHeader roh
RIGHT OUTER JOIN 
(SELECT rod.id rod_id ,key_id,key_name ,key_value ,expected_close_date ,wty_dept ,header_id,date_updated
FROM OpenROData rod
RIGHT OUTER JOIN OpenRONotes ron 
ON rod.key_value=ron.ro_number 
ORDER BY ron.date_updated ) tab 
ON roh.id=header_id WHERE 1=1 AND
roh.customer_id='193'
ORDER BY date_updated DESC LIMIT 1;

上面的查询返回了最新记录,其中wty_dept列为NULL。 检查并享受编码:) !!