Mysql SQL选择以消除重复项并返回子表上记录的最新日期
我试图从主表、我的表单以及通过linktable链接的表中检索数据。actions表可能包含多个action_required='Close'记录作为标题记录 这是我的三张桌子:Mysql SQL选择以消除重复项并返回子表上记录的最新日期,mysql,Mysql,我试图从主表、我的表单以及通过linktable链接的表中检索数据。actions表可能包含多个action_required='Close'记录作为标题记录 这是我的三张桌子: my_form: # idmy_form, summary, description, station '1', 'OSR puncture', 'Puncture while driving to work', 'Thornbury' '2', 'Windscreen wiper broke', 'Wiper bro
my_form:
# idmy_form, summary, description, station
'1', 'OSR puncture', 'Puncture while driving to work', 'Thornbury'
'2', 'Windscreen wiper broke', 'Wiper broke while going shopping', 'Bristol'
'3', 'Out of screenwash', 'Run out of screen wash en route to Cardiff', 'Cardiff'
form_action:
# idmy_form, action_id
'1', '201'
'1', '202'
'1', '203'
'2', '301'
'2', '302'
'3', '401'
'3', '402'
'3', '403'
'3', '404'
'3', '405'
actions:
# action_id, action_detail, action_required, action_date
'201', 'Fix', 'Open', '2013-01-01 00:00:00'
'202', 'Fix', 'Amend', '2013-01-04 00:00:00'
'203', 'Fix', 'Close', '2013-01-06 00:00:00'
'301', 'Fix', 'Open', '2013-03-01 00:00:00'
'302', 'Fix', 'Review', '2013-04-12 00:00:00'
'401', 'Fix', 'Open', '2013-09-04 00:00:00'
'402', 'Fix', 'Review', '2013-09-12 00:00:00'
'403', 'Fix', 'Close', '2013-09-17 00:00:00'
'404', 'Fix', 'Reopen', '2013-09-21 00:00:00'
'405', 'Fix', 'Close', '2013-09-23 00:00:00'
到目前为止,我拥有的sql是:
SELECT
mf.idmy_form,
mf.summary,
mf.station,
a.action_id,
a.action_required,
a.action_date
FROM my_form mf
LEFT JOIN (
SELECT
act.action_id,
act.action_required,
act.action_date,
fa.idmy_form
FROM form_action fa
JOIN actions act
ON fa.action_id = act.action_id
AND act.action_required = 'Close'
) a
ON a.idmy_form = mf.idmy_form
这将返回以下结果:
# idmy_form, summary, station, action_id, action_required, action_date
'1', 'OSR puncture', 'Thornbury', '203', 'Close', '2013-01-06 00:00:00'
'2', 'Windscreen wiper broke', 'Bristol', NULL, NULL, NULL
'3', 'Out of screenwash', 'Cardiff', '403', 'Close', '2013-09-17 00:00:00'
'3', 'Out of screenwash', 'Cardiff', '405', 'Close', '2013-09-23 00:00:00'
理想情况下,我只希望检索每个标题记录的最新截止日期,其中相关操作有一个action\u required='Close'。从上面的结果中去掉第三行
我已尝试在内部选择中添加group by,但它会抛出一个oracle而不是缺少右括号的group by表达式。添加一个子查询以获取
MAX()
日期。下面介绍了更多实现此目的的方法
SELECT
mf.idmy_form,
mf.summary,
mf.station,
a.action_id,
a.action_required,
a.action_date
FROM my_form mf
LEFT JOIN (
SELECT
act.action_id,
act.action_required,
act.action_date,
fa.idmy_form
FROM form_action fa
JOIN actions act
ON fa.action_id = act.action_id
AND act.action_required = 'Close'
WHERE action_date = (SELECT MAX(action_date)
FROM actions
JOIN form_action USING(action_id)
WHERE actions.action_required = 'Close'
AND fa.idmy_form = form_action.idmy_form)
) a
ON a.idmy_form = mf.idmy_form
- 现场观看它的工作
explain
的结果和show create table\G