从列中选择唯一值

时间:2011-12-20 07:08:34

标签: php mysql sql

我有一个MySQL表,其中包含以下类型的信息:

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

以下是我用来从此表中获取数据的脚本示例:

<?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);
?> 

此脚本显示表格中的每个日期,例如

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

我想只显示唯一的日期,例如

12.dec.2011
10.dec.2011

9 个答案:

答案 0 :(得分:341)

在MySQL中使用DISTINCT运算符:

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

答案 1 :(得分:42)

使用

SELECT DISTINCT Date FROM buy ORDER BY Date

所以MySQL删除重复

BTW:在SELECT中使用显式列名,当你从MySQL获得大量结果时,在PHP中使用较少的资源

答案 2 :(得分:25)

使用此查询获取值

SELECT * FROM `buy` group by date order by date DESC

答案 3 :(得分:19)

其余几乎是正确的,除非他们应该按Date DESC命令

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

答案 4 :(得分:6)

DISTINCT始终是获取唯一值的正确选择。您也可以在不使用它的情况下进行替换。那是GROUP BY。它只是在查询结尾添加,后跟列名。

SELECT * FROM buy GROUP BY date,description

答案 5 :(得分:3)

另一个DISTINCT答案,但有多个值:

SELECT DISTINCT `field1`, `field2`, `field3` FROM `some_table`  WHERE `some_field` > 5000 ORDER BY `some_field`

答案 6 :(得分:2)

使用类似这样的内容,以防您还希望将每个日期的产品详细信息输出为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"}}

SQL Fiddle

中试用

答案 7 :(得分:0)

取决于您的需求。

在这种情况下,我建议:

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

因为字段很少而且DISTINCT的执行时间低于GROUP BY的执行时间。

在其他情况下,例如,在有很多字段的地方,我更喜欢:

SELECT * FROM buy GROUP BY date ORDER BY date DESC;

答案 8 :(得分:0)

实现相同的关键字有一个特定的关键字。

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