想象一下下面的MySQL订单表:
id | name
1 | Mike
2 | Steve
3 | Janet
4 | Juliet
5 | Mike
6 | Jane
这是我目前的查询:
SELECT * FROM table ORDER BY id DESC
但是,我想通过name
对这些内容进行“分组”,这样我就可以从同一个人那里获得相同的订单,但是,我无法进行ORDER BY name
。
这是我想要的输出:
id | name
6 | Jane
5 | Mike
1 | Mike
4 | Juliet
3 | Janet
2 | Steve
这个输出的查询是什么?
答案 0 :(得分:3)
E.g:
SELECT y.id
, y.name
FROM my_table x
JOIN my_table y
ON y.name = x.name
GROUP
BY name
, id
ORDER
BY MAX(x.id) DESC
, id DESC;
答案 1 :(得分:2)
您需要进行特殊计算才能获得行位置。
SELECT a.*
FROM tableName a
INNER JOIN
(
SELECT Name,
@ord := @ord + 1 ord
FROM
(
SELECT MAX(ID) ID, NAME
FROM TableName
GROUP BY Name
) a, (SELECT @ord := 0) b
ORDER BY ID DESC
) b ON a.Name = b.Name
ORDER BY b.ord, a.ID DESC
答案 2 :(得分:1)
您可以通过双ORDER BY
:
SELECT * FROM t ORDER BY name ASC, id DESC
答案 3 :(得分:0)
SELECT * FROM table1
ORDER BY field(NAME,'Mike','Jane') desc,
`ID` desc;
<强> exactly as you asked 强>
答案 4 :(得分:0)
如果您想拥有更通用的SQL,也可以尝试此查询。
SELECT id, name
FROM ( SELECT id, name, (SELECT MAX(id) from Table1 where name=t.name) AS max_id
FROM Table1 AS t
ORDER BY max_id DESC, id DESC) as x
答案 5 :(得分:-1)
如何使用group by? 您可以按名称对其进行分组,然后订购......