我有一个数据库表,其中包含在指定smlouva
上执行的操作列表。我需要的是选择为每个smlouva
执行的最新/最新操作,这些操作受时间范围和操作类型的限制。
行动表如下:
ID (int, Primary), action_ID(int), date(datetime), smlouvy_id(int)
还有一些数据:
id action date smlouva_id
617872 -9 2016-08-25 08:43:00 114779
617871 -9 2016-08-25 08:43:00 114778
617867 -1 2016-08-25 08:30:00 114777
617865 -1 2016-08-25 08:27:00 114777
617864 -9 2016-08-25 08:27:00 114777
617839 -1 2016-08-25 08:24:00 114776
617838 -9 2016-08-25 08:23:00 114776
617837 105 2016-08-25 08:23:00 114775
我想要应用的约束是:
在这些约束中,我想为每个smlouva_id
- 最近date
的行选择最新/最新行。实际上,我只需要该行的smlouva_id
和action
。
因此对于这些数据,正确的结果将是:
id action date smlouva_id
617872 -9 2016-08-25 08:43:00 114779
617871 -9 2016-08-25 08:43:00 114778
617864 -9 2016-08-25 08:27:00 114777
617838 -9 2016-08-25 08:23:00 114776
617837 105 2016-08-25 08:23:00 114775
或者同样充足:
action smlouva_id
-9 114779
-9 114778
-9 114777
-9 114776
105 114775
我已经尝试了几个命令,但是它们似乎都没有工作。
SELECT action, smlouva_id
FROM `pov_action` AS `O`
WHERE (
SELECT MAX(`date`)
FROM `pov_action` AS `I`
WHERE (
(I.action = 100)
OR (I.action = 101)
OR (I.action = 104)
OR (I.action = 105)
OR (I.action = 106)
OR (I.action = 102)
OR (I.action = 103)
OR (I.action = -9)
)
AND (I.`smlouva_id` = O.`smlouva_id`)
)
AND (date >= '2016-08-25 08:28:07')
或者这个:
SELECT action, smlouva_id
FROM `pov_action`
WHERE (date >= '2016-08-25 09:23:09')
AND (
(action = 100)
OR (action = 101)
OR (action = 104)
OR (action = 105)
OR (action = 106)
OR (action = 102)
OR (action = 103)
OR (action = -9)
)
GROUP BY `smlouva_id`
(HAVING date = MAX(date)) -- optionally does not work with nor without
ORDER BY chdate DESC
服务器版本:5.5.50-MariaDB MariaDB服务器
答案 0 :(得分:1)
使用派生表,使用GROUP BY
查找每个smlouva_id的最后日期。
JOIN
表格中包含该结果:
select t1.*
from tablename t1
join (select smlouva_id, max(date) as maxdate
from tablename
where action in (100, 101 ,104, 105, 106, 102, 103, -9)
group by smlouva_id) t2
ON t1.smlouva_id = t2.smlouva_id and t1.date = t2.maxdate
where t1.action in (100, 101 ,104, 105, 106, 102, 103, -9)