如何按数据库中的上一个日期排序?

时间:2011-11-08 10:15:23

标签: php mysql

我想问的是如何从数据库记录和我的PHP代码中选择能够按日期排序以前的日期,这是我想在我的界面中显示的内容:

2011-10-01

2011-10-01

2011-10-01

something here..


2011-10-02

2011-10-02

something here..


2011-10-03

something here..

在我的数据库中,前一个日期有很多重复日期,有些只有一条记录,所以我需要对它进行排序以使我的界面更清晰

这是我的代码(但它不起作用):

$Current = date("Y-m-d" ,strtotime("now"));

$query= mysql_query("SELECT date FROM staff WHERE date < '$Current'");
while($res=mysql_fetch_array($query)){
echo $res['date'];
echo "something here";
}

感谢

4 个答案:

答案 0 :(得分:1)

你不能简单地使用它吗?

SELECT `date` FROM staff WHERE `date` < NOW() ORDER BY `date`

或(如果您只需要不同的日期)

SELECT DISTINCT `date` FROM staff WHERE `date` < NOW() ORDER BY `date`

答案 1 :(得分:0)

("SELECT count(*), date FROM staff WHERE date < '$Current' GROUP BY date ORDER BY date asc"); 

将它们与计数分组,然后您可以将每个日期写出计数所指示的次数,然后写出您的附加值。

答案 2 :(得分:0)

认为您可以通过对数据库中的结果进行排序并通过分组删除重复项来实现您的目标

SELECT date FROM staff WHERE date < '$Current' ORDER BY date ASC GROUP BY date;

答案 3 :(得分:0)

您需要的代码非常简单。
你只需要了解循环的含义并在迭代之间“记住”状态

//a variable to remember the old date
$olddate = '';
//i named this variable $sql because it actually contains an sql query
$sql = "SELECT date FROM staff WHERE date < '$Current'";
//I named this variable $res because it actually contains NOT sql query, but mysql RESource.
$res = mysql_query($sql) or treigger_error(mysql_error()." ".$sql);
//I named this variable $row because it actually represents a row from the database.
while($row=mysql_fetch_array($res)) {
  if ($olddate and $olddate != $row['date']) {
    echo "something here";
  }
  echo $row['date'];
  $olddate = $row['date'];
}