seleccionar valores únicos de una columna


Tengo una tabla MySQL que contiene el siguiente tipo de información:

    Date            product 
2011-12-12           azd
2011-12-12           yxm
2011-12-10           sdx
2011-12-10           ssdd  

Aquí hay un ejemplo de un script que uso para obtener datos de esta tabla:

<?php

$con = mysql_connect("localhost","username","password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("db", $con);
$sql=mysql_query("SELECT * FROM buy ORDER BY Date");
while($row = mysql_fetch_array($sql))
{

 echo "<li><a href='http://www.website/". $row['Date'].".html'>buy ". date("j, M Y", strtotime($row["Date"]))."</a></li>";

    }
    mysql_close($con);
?> 

Este script muestra cada fecha de la tabla, por ejemplo,

12.dec 2011
12.dec.2011
10.dec.2011
10.dec.2011

Me gustaría mostrar solo fechas únicas, por ejemplo,

12.dec.2011
10.dec.2011
 174
Author: ivanleoncz, 2011-12-20

9 answers

Use el operador DISTINCT en MySQL:

SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;
 329
Author: Léon Rodenburg,
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-05-14 06:44:46

Use

SELECT DISTINCT Date FROM buy ORDER BY Date

Entonces MySQL elimina duplicados

POR cierto: usar nombres de columna explícitos en SELECT usa menos recursos en PHP cuando obtiene un resultado grande de MySQL

 40
Author: rabudde,
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-05-14 19:27:06

Utilice esta consulta para obtener valores

SELECT * FROM `buy` group by date order by date DESC
 25
Author: John,
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-08-24 18:47:54

El resto son casi correctos, excepto que deben ordenar por Fecha DESC

SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;
 19
Author: ajreal,
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
2011-12-20 07:18:30

DISTINCT siempre es una elección correcta para obtener valores únicos. También puede hacerlo alternativamente sin usarlo. Eso es GROUP BY. Que tiene simplemente agregar al final de la consulta y seguido por el nombre de la columna.

SELECT * FROM buy GROUP BY date,description
 6
Author: Kvvaradha,
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-04-07 05:36:56

Otra DISTINCT respuesta, pero con múltiples valores:

SELECT DISTINCT `field1`, `field2`, `field3` FROM `some_table`  WHERE `some_field` > 5000 ORDER BY `some_field`
 3
Author: Pedro Lobito,
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
2017-11-22 12:37:25

Use algo como esto en caso de que también desee generar detalles de productos por fecha como JSON.

SELECT `date`,
CONCAT('{',GROUP_CONCAT('{\"id\": \"',`product_id`,'\",\"name\": \"',`product_name`,'\"}'),'}') as `productsJSON`
FROM `buy` group by `date` 
order by `date` DESC

 product_id product_name     date  
|    1     |     azd    | 2011-12-12 |
|    2     |     xyz    | 2011-12-12 |
|    3     |     ase    | 2011-12-11 |
|    4     |     azwed  | 2011-12-11 |
|    5     |     wed    | 2011-12-10 |
|    6     |     cvg    | 2011-12-10 |
|    7     |     cvig   | 2011-12-09 |

RESULT
       date                                productsJSON
2011-12-12T00:00:00Z    {{"id": "1","name": "azd"},{"id": "2","name": "xyz"}}
2011-12-11T00:00:00Z    {{"id": "3","name": "ase"},{"id": "4","name": "azwed"}}
2011-12-10T00:00:00Z    {{"id": "5","name": "wed"},{"id": "6","name": "cvg"}}
2011-12-09T00:00:00Z    {{"id": "7","name": "cvig"}}

Pruébelo en Violín SQL

 2
Author: Peter Darmis,
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
2017-11-22 15:06:38

Hay una palabra clave específica para el logro de la misma.

SELECT DISTINCT( Date ) AS Date 
FROM   buy 
ORDER  BY Date DESC; 
 0
Author: Ashutosh dwivedi,
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
2017-11-29 15:41:11

Depende de lo que necesites.

En este caso sugiero:

SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;

Porque hay pocos campos y el tiempo de ejecución de DISTINCT es menor que la ejecución de GROUP BY.

En otros casos, por ejemplo, donde hay muchos campos, prefiero:

SELECT * FROM buy GROUP BY date ORDER BY date DESC;
 0
Author: Marco Desposito,
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
2017-11-29 16:39:25