php + mysql,按名称排序+从特定id开始

时间:2022-10-28 21:46:11

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:

我想做的是,我想从id:3开始,所以它应该输出:

3,4,5,1,2

2 个解决方案

#1


6  

EDIT : Mark is correct. The earlier query was syntactically incorrect. Using dummy aliasés should work!

编辑:马克是正确的。早期的查询在语法上是不正确的。使用虚拟别名应该有效!

Select id from
(
    SELECT id FROM table_name 
    WHERE id >= 3 
    ORDER BY id ASC
) X   

UNION

Select * from
(
    SELECT id FROM table_name 
    WHERE id < 3 
    ORDER BY id ASC
) Y

This should give you 3,4,5,1,2

这应该给你3,4,5,1,2

#2


12  

You can use an expression in the ORDER BY:

您可以在ORDER BY中使用表达式:

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

Result:

3  Shawn
4  Ryan
5  Seth
1  Joe
2  Craig

I'd also advise you not to use SELECT * and instead to list the columns explicitly.

我还建议你不要使用SELECT *而是明确列出列。

#1


6  

EDIT : Mark is correct. The earlier query was syntactically incorrect. Using dummy aliasés should work!

编辑:马克是正确的。早期的查询在语法上是不正确的。使用虚拟别名应该有效!

Select id from
(
    SELECT id FROM table_name 
    WHERE id >= 3 
    ORDER BY id ASC
) X   

UNION

Select * from
(
    SELECT id FROM table_name 
    WHERE id < 3 
    ORDER BY id ASC
) Y

This should give you 3,4,5,1,2

这应该给你3,4,5,1,2

#2


12  

You can use an expression in the ORDER BY:

您可以在ORDER BY中使用表达式:

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

Result:

3  Shawn
4  Ryan
5  Seth
1  Joe
2  Craig

I'd also advise you not to use SELECT * and instead to list the columns explicitly.

我还建议你不要使用SELECT *而是明确列出列。