Mysql按值排序

时间:2013-06-20 09:40:40

标签: mysql sql-order-by

我有桌子:

posts: id |作者|内容

我需要用一个查询从这个表中选择所有条目,但是作者“demo”写的帖子必须在第一个。

3 个答案:

答案 0 :(得分:1)

SELECT * FROM posts 
ORDER BY CASE 
    WHEN author = 'demo' THEN posts
END DESC

demo

如果你想在这里订购别人的另一个例子:

 _______________________________________________________________________________
|                                                                               |
|                                                                               |
|      SELECT * FROM post ORDER BY                                              |
|       CASE                                                                    |
|       WHEN author = 'demo' THEN post1                                         |
|       WHEN author = 'sdvg' THEN id                                            |
|       END DESC                                                                |
|                                                                               |
|_______________________________________________________________________________|

demo

答案 1 :(得分:1)

我使用UNION并使用预定义值来ORDER BY。 通过demo 1st选择所有帖子,然后选择不通过demo

的帖子
SELECT id, author, content, 1 AS special FROM posts WHERE author='demo'
UNION
SELECT id, author, content, 0 AS special FROM posts WHERE author<>'demo'
ORDER BY special DESC

答案 2 :(得分:0)

如果您想将作者字段作为第一个,那么您必须编写

select author, id, content FROM posts ORDER BY author

否则

select * FROM posts order by author