选择min和max,在mysql中按天分组过滤器

时间:2015-03-18 16:59:28

标签: mysql

我想优化此查询:

SELECT id_local, 
       id2 cardnum, 
       Date_format(paneldate, '%Y-%m-%d') date, 
       (SELECT Min(Date_format(C2.paneldate, '%H:%i:%s')) 
        FROM   doors C2 
        WHERE  C2.id2data = doors.id2data 
               AND Date_format(C2.paneldate, '%Y-%m-%d') = Date_format(doors.paneldate, '%Y-%m-%d') 
               AND C2.id1data IN( 'entry1', 'entry2' )) timefistentry, 
       (SELECT Max(Date_format(C3.paneldate, '%H:%i:%s')) 
        FROM   gestionhumana.gestion_puertas C3 
        WHERE  C3.id2data = doors.id2data 
               AND Date_format(C3.paneldate, '%Y-%m-%d') = Date_format(doors.paneldate, '%Y-%m-%d') 
               AND C3.id1data = 'exit1') timeexit, 
       Substring_index(id2data, '%', 1) name, 
       id1data puerta 
FROM   doors 
WHERE  Date_format(paneldate, '%Y-%m-%d') >= Date_sub(Curdate(), interval 4 day) 
GROUP  BY Date_format(paneldate, '%Y%m%d'), 
          id2data 
ORDER  BY paneldate DESC   

我试图让第一次一个人穿过门并且最后一次穿过出口门时,它们是不同的门,但是在不同的记录中记录在同一个表中,查询有效但是它花了太长时间。一个人可以多次过门。

EDT。改变了表的名称。 date_format(paneldate,'%Y-%m-%d')和(Date_format(C2.paneldate,'%H:%i:%s')是因为paneldate是datetime类型,并包含注册表的小时分钟和秒,我不能改变表格,我需要几天来填充它们。

id_local是来自de table的id id2是卡的号码 paneldate每行的日期时间 门的id1data名称(entri1,entry2,exit1) id2data人的名字。  一个人可以有很多卡,但我想要按人和白天获得。

1 个答案:

答案 0 :(得分:0)

这是我的新例子。它应该比你的更快(我希望)。

SELECT
    entries.id_local,
    entries.id2 AS cardnum,
    DATE_FORMAT(MIN(entries.paneldate), '%H:%i:%s') AS timefistentry,
    DATE_FORMAT(MAX(exits.paneldate), '%H:%i:%s') AS timeexit,
    SUBSTRING_INDEX(entries.id2data, '%', 1) AS name,
    entries.id1data AS puerta
FROM doors AS entries
LEFT JOIN (SELECT paneldate, id2data FROM doors WHERE id1data = 'exit1') AS exits ON
    entries.id2data = exits.id2data AND
    DATE_FORMAT(entries.paneldate, '%Y-%m-%d') = DATE_FORMAT(exits.paneldate, '%Y-%m-%d')
WHERE
    DATE_FORMAT(entries.paneldate, '%Y-%m-%d') >= DATE_SUB(CURDATE(), INTERVAL 4 DAY) AND
    entries.id1data IN( 'entry1', 'entry2' )
GROUP BY DATE_FORMAT(entries.paneldate, '%Y%m%d'), entries.id2data
ORDER BY entries.paneldate DESC

据我了解你;每当有人通过门时,门名(id1data),时间(paneldate)和人名(id2data)都保存在新行上。每个传递都将保存到同一个表中,唯一将出口与条目分开的是列id1data,它包含一个带有门名称的字符串(exit1,entry1和entry2)。