mysql过虑最大时间,获取行由最新时间的MySQL过滤

I have a question of a complex query and I don't know how to write it.

I have the next table:

+---------------+-----------+----------+--------------------------+

|id_incidencia | id_alarma | idaction | concat(fecha, ' ', hora) |

+---------------+-----------+----------+--------------------------+

| 18488 | 551 | 1 | 2016-08-29 14:55:47 |

| 18491 | 551 | 7 | 2016-08-29 15:02:47 |

| 18493 | 551 | 6 | 2016-08-29 15:37:39 |

| 18495 | 551 | 7 | 2016-08-29 15:41:27 |

| 19263 | 551 | 6 | 2016-09-16 15:17:27 |

| 19429 | 5151 | 5 | 2016-09-19 09:01:17 |

| 19447 | 5151 | 5 | 2016-09-19 09:25:23 |

| 19500 | 5151 | 5 | 2016-09-20 09:38:11 |

| 19532 | 5151 | 5 | 2016-09-23 15:02:50 |

| 19526 | 5151 | 6 | 2016-09-23 11:23:27 |

| 19528 | 5151 | 6 | 2016-09-23 11:28:01 |

| 19527 | 5151 | 7 | 2016-09-23 11:25:18 |

| 19529 | 5151 | 7 | 2016-09-23 11:28:08 |

+---------------+-----------+----------+--------------------------+

I'd like to have the next result from a query:

idaction | id_alarma | datetime

---------+-----------+---------

7 | 551 | 2016-08-29 15:41:27

7 | 5151 | 2016-09-23 11:28:08

That's means that I want for each group of id_alarma value, I want to get the last row with the most recently time and it's value of idaction. The problem is that when I perform the next query, the value in idaction is not the same that match with the datetime field.

The query that I mention is:

SELECT a.id,

nia.idaction,

MAX(CONCAT(nia.fecha, ' ', nia.hora))

FROM nectar_incidencias_alarma nia

INNER JOIN alarmas a

ON a.id=nia.id_alarma

WHERE nia.idaction IN (6,7)

GROUP BY a.id

解决方案

To retrieve the correct value of idaction, you could use group_concat in combination with substring_index. Note that you don't really need to join the table alarmas, as you have all you need in nectar_incidencias_alarma:

SELECT id_alarma,

SUBSTRING_INDEX(GROUP_CONCAT(idaction

ORDER BY CONCAT(fecha, ' ', hora) DESC), ',', 1)+0 id_action,

MAX(CONCAT(fecha, ' ', hora))

FROM nectar_incidencias_alarma

WHERE idaction IN (6,7)

GROUP BY id_alarma

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值