开发者

Amend MySQL Query to force a record to appear first?

I have the following:

"SELECT * FROM pages WHERE parent=0 ORDER BY `sort` ASC"

There is a bug somewhere in the system I am working with which means that a page can have a lower sort value than the home page. I am currently lookin开发者_运维百科g into this, in the meantime i need the query to enforce that home page comes out first.

Can this query be adapted so it always get's the page with an id of 1 to appear first, then rest are sorted by the sort column?


SELECT  *
FROM    pages
ORDER BY
        id = 1 DESC, sort

If you are going to apply a LIMIT clause to this query, it may be better to split it in two:

SELECT  *
FROM    pages
WHERE   id = 1
UNION ALL
SELECT  *
FROM    (
        SELECT  *
        FROM    pages
        WHERE   parent = 0
                AND id <> 1
        ORDER BY
                parent, sort
        LIMIT 9
        )

so that an index on (parent, sort) can be used.


SELECT * FROM pages WHERE parent=0 ORDER BY IF( id = 1, -1, 0 ) ASC, id ASC


SELECT * FROM pages WHERE parent=0 ORDER BY `id` ASC, `sort` ASC
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜