仅从重复值列中选择一行

时间:2017-04-22 17:39:12

标签: php sql

[ title   -    date  ]
[  PHP    -  10/10/10]
[  PHP    -  10/10/11]
[  PDO    -  10/10/12]
[  ASP    -  10/10/13]
[  ASP    -  10/10/16]
[  PHP    -  10/10/18]

当我使用此查询时,从此表中

$query = "SELECT DISTINCT title, date FROM posts WHERE title = :title ORDER BY title, date";

然后去

Prepare
Execute
while($row = $stmt->fetch()) {
  $title = $row['title'];
  $date = $row['date'];

  echo "<div>$title</div><div>$date</div>";
 }

我仍然获得所有值,而不仅仅是一个标题为PHP的值,我只想选择具有最高日期的值

我希望它是

<div>ASP</div><div>10/10/16</div>
<div>PDO</div><div>10/10/12</div>
<div>PHP</div><div>10/10/18</div>

2 个答案:

答案 0 :(得分:2)

看起来像一个简单的聚合:

SELECT title, MAX(date) 
FROM posts 
GROUP BY title
ORDER BY title

答案 1 :(得分:0)

如果您只想要一行,请使用limit 1

SELECT title, date
FROM posts
WHERE title = :title
ORDER BY date DESC
LIMIT 1;