MySQL Order from a starting value

时光总嘲笑我的痴心妄想 提交于 2019-12-05 16:08:23

This is the answer I was looking for. I hope I am not downvoted for this but I managed to resolve this.

Let me explain again simpler terms. MySQL ORDER BY + Start with..

MySQL:

id | name  |
------------
1  | Joe   |
2  | Craig |
3  | Shawn |
4  | Ryan  |
5  | Seth  |

PHP:

$a = mysql_query("SELECT * FROM table_name ORDER BY name DESC");

what I want to do though is, I want to start at id: 3, so it should output:

3,4,5,1,2

Solution 1

SELECT id, name
FROM table_name
ORDER BY id < 3, id

Result:

3  Shawn
4  Ryan
5  Seth
1  Joe
2  Craig

Solution 2

You can use FIELD, eg

SELECT * 
FROM products 
ORDER BY FIELD(`order`, 6) ASC

WHERE condition should come before ORDER BY clause

SELECT * 
FROM products 
WHERE START_VALUE = '6' 
ORDER BY order

As a sidenote, ORDER is a RESERVED keyword. One way to escape it is by wrapping with backtick. eg,

SELECT * 
FROM products 
WHERE START_VALUE = '6' 
ORDER BY `order`

Another is by supplying an ALIAS

SELECT * 
FROM products p
WHERE START_VALUE = '6' 
ORDER BY p.order

but looking back at your question, you want to custom order the data right? You can use FIELD, eg

SELECT * 
FROM products 
ORDER BY FIELD(`order`, 6) ASC

please clear your question. if you want all records, use query like below...

SELECT * FROM products WHERE ORDER BY COLOURID ASC, order DESC

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!