通过desc选择不同的值顺序

时间:2013-10-12 12:21:47

标签: mysql sql

我希望customer_ids.no选择不同的time订单,或者无论如何

s.no     customer_id         time
1        3                   100001
2        2                   100002
3        4                   100003
4        3                   100004
5        2                   100005

我正在使用

select distinct(customer_id) from table_name order by time DESC

并且答案为4 2 3,但我希望它应该是2 3 4

3 个答案:

答案 0 :(得分:15)

所以你的问题陈述是“你想要的customer_id列表,按其最大时间值的降序排序”,对吗?

SELECT customer_id, MAX(time)
FROM table_name
GROUP BY customer_id
ORDER BY MAX(time) DESC

答案 1 :(得分:0)

你必须做这样的第二次选择:

SELECT
    `number`
FROM
(
    SELECT
        DISTINCT(number) AS number
    FROM
        `table_name`
    ORDER BY
        `time` DESC
) AS `temp`
ORDER BY
    `number` ASC

答案 2 :(得分:0)

可以使用第二个查询

完成
$query = "SELECT * 
            FROM (SELECT customer_id
                FROM table_name                 
                ORDER BY customer_id DESC) as rows              
            GROUP BY customer_id";