MySQL SELECT * WHERE timestamp = TODAY


Estoy tratando de seleccionar solo los registros de hoy de una tabla de base de datos.

Actualmente utilizo

SELECT * FROM `table` WHERE (`timestamp` > DATE_SUB(now(), INTERVAL 1 DAY));

Pero esto toma los resultados de las últimas 24 horas, y lo necesito para seleccionar solo los resultados de hoy, ignorando el tiempo. ¿Cómo puedo seleccionar los resultados solo en función de la fecha ?

Author: 2Dee, 2013-02-08

8 answers

Use DATE y CURDATE()

SELECT * FROM `table` WHERE DATE(`timestamp`) = CURDATE()

Supongo que usando DATE todavía usa INDEX .

Ver el plan de ejecución en la DEMO

 142
Author: John Woo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-08 09:39:39

Si desea que se use un índice y la consulta no haga un análisis de tabla:

WHERE timestamp >= CURDATE()
  AND timestamp < CURDATE() + INTERVAL 1 DAY

Para mostrar la diferencia que esto hace en los planes de ejecución reales, probaremos con un SQL-Violín (un sitio extremadamente útil):

CREATE TABLE test                            --- simple table
    ( id INT NOT NULL AUTO_INCREMENT
    ,`timestamp` datetime                    --- index timestamp
    , data VARCHAR(100) NOT NULL 
          DEFAULT 'Sample data'
    , PRIMARY KEY (id)
    , INDEX t_IX (`timestamp`, id)
    ) ;

INSERT INTO test
    (`timestamp`)
VALUES
    ('2013-02-08 00:01:12'),
    ---                                      --- insert about 7k rows
    ('2013-02-08 20:01:12') ;

Vamos a probar las 2 versiones ahora.


Versión 1 con DATE(timestamp) = ?

EXPLAIN
SELECT * FROM test 
WHERE DATE(timestamp) = CURDATE()            ---  using DATE(timestamp)
ORDER BY timestamp ;

Explica:

ID  SELECT_TYPE  TABLE  TYPE  POSSIBLE_KEYS  KEY  KEY_LEN  REF 
1   SIMPLE       test   ALL

ROWS  FILTERED  EXTRA
6671  100       Using where; Using filesort

Filtra todas las filas (6671) y luego hace un filesort (eso no es un problema como las filas devueltas son pocas)


Versión 2 con timestamp <= ? AND timestamp < ?

EXPLAIN
SELECT * FROM test 
WHERE timestamp >= CURDATE()
  AND timestamp < CURDATE() + INTERVAL 1 DAY
ORDER BY timestamp ;

Explica:

ID  SELECT_TYPE  TABLE  TYPE  POSSIBLE_KEYS  KEY  KEY_LEN  REF 
1   SIMPLE       test   range t_IX           t_IX    9 

ROWS  FILTERED  EXTRA
2     100       Using where

Utiliza un escaneo de rango en el índice, y luego lee solo las filas correspondientes de la tabla.

 44
Author: ypercubeᵀᴹ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-08 13:31:44
SELECT * FROM `table` WHERE timestamp >= CURDATE()

Es más corto, no hay necesidad de usar 'AND timestamp

Porque CURDATE () siempre devuelve el día actual

MySQL CURDATE () Function

 5
Author: Hamed Persia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-07 15:56:45

Simplemente colóquelo en una fecha:

SELECT * FROM `table` WHERE CAST(`timestamp` TO DATE) == CAST(NOW() TO DATE)
 1
Author: MarcDefiant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-08 09:07:44

¿De cuántas maneras podemos despellejar a este gato? Aquí hay otra variante.

SELECCIONE * DESDE table DONDE FECHA (FROM_UNIXTIME(timestamp)) = '2015-11-18';

 1
Author: stefgosselin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-19 03:56:13

Si desea comparar con una fecha en particular, puede escribirla directamente como:

Seleccione * desde table_name donde timestamp > = '2018-07-07';

/ / aquí la marca de tiempo es el nombre de la columna que tiene el tipo como marca de tiempo

o

Para obtener la fecha de hoy , la función CURDATE() está disponible, por lo que:

Seleccione * desde table_name donde timestamp > = CURDATE ();

 0
Author: ViditAgarwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-07 21:43:45

En Visual Studio 2017, usando la base de datos incorporada para el desarrollo tuve problemas con la solución dada actual, tuve que cambiar el código para que funcionara porque arrojó el error de que DATE() no era una función incorporada.

Aquí está mi solución:

where CAST(TimeCalled AS DATE) = CAST(GETDATE() AS DATE)

 0
Author: Cesar Bourdain Costa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-09 15:37:19

Esto podría ser lo más fácil en mi opinión:

SELECT * FROM `table` WHERE `timestamp` like concat(CURDATE(),'%');
 -1
Author: Jerry Jones,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-26 09:28:51