获取db中条目的“第n个”

时间:2016-01-05 04:29:34

标签: php mysql

我有一个客户订单数据库。我希望回应所有订单的结果,但当它是回头客时,我想看看特定订单是否是他们的第二,第三等。

例如:

|--id--name---date------|
|---1--Eric---01-01-16--|
|---2--Bob----01-02-16--|
|---3--Mary---01-03-16--|
|---4--Bob----01-04-16--|

PHP:

$result = $mysqli->query('
    SELECT 
        name, 
        details 
    FROM 
        table 
    ORDER BY 
        date DESC
');
while($echo = $result->fetch_object()) {
    echo $echo->name.$echo->details.'<br>';
}

结果:

Bob - Order details *Second purchase
Mary - Order details
Bob - Order details
Eric - Order details

1 个答案:

答案 0 :(得分:0)

您可以使用以下sql查询来获取其排名的订单:

Select Id, Name, Date,
( 
                CASE Name 
                WHEN @curName 
                THEN @curRow := @curRow + 1 
                ELSE @curRow := 1 AND @curName := Name END
              ) + 1 AS rank
from  orders o,  (SELECT @curRow := 0, @curName := '') r
Group BY Name, Date, Id
Order BY Name, date asc

SQL Fiddle