mysql查询PHP:我希望先将特定项目排序,然后对其余项目

时间:2017-01-21 11:38:51

标签: php mysql

我有下表。

id  | car_name | owner
-------------------------
1   | Toyota   | Jan
2   | Ford     | Mike
3   | Isuzu    | Andrew
4   | BMW      | Jan
5   | Ferrari  | Steve
6   | Audi     | Jan
7   | Benz     | Klark
8   | Hyundai  | Jan
9   | Kia      | Jan

我想得到所有的车主,但Jan有5辆车,我希望Jan的前四项列入名单。我不关心我收到其余项目的顺序。像这样。

id  | car_name | owner
-------------------------
1   | Toyota   | Jan
4   | BMW      | Jan
7   | Benz     | Jan
8   | Hyundai  | Jan
2   | Ford     | Mike
3   | Isuzu    | Andrew
5   | Ferrari  | Steve
6   | Audi     | Bob
9   | Kia      | Jan

我该怎么做?感谢

3 个答案:

答案 0 :(得分:1)

您可以通过以下任何一种方式订购

order by owner <> 'Jan'
order by owner = 'Jan' desc
order by case when owner = 'Jan' then 0 else 1 end
order by if(owner = 'Jan',0,1)

owner = 'Jan'1生成True,为0生成False,因此desc

此外,由于您不关心除前四行之外的其余行的顺序,因此您可以继续保留Jan行的其余部分。

试试这个:

SELECT 
    id, car_name, owner
FROM
    ((SELECT 
        0 x, t.*
    FROM
        your_table t
    ORDER BY owner <> 'Jan' , id
    LIMIT 4) UNION ALL (SELECT 
        *
    FROM
        (SELECT 
        1 x, t.*
    FROM
        your_table t
    ORDER BY owner <> 'Jan' , id
    LIMIT 4 , 1000) t
    ORDER BY id)) t
ORDER BY x , id;

仅当Jan有4行或更多行时才有效。

SQLFiddle

答案 1 :(得分:0)

SELECT * FROM `table_name` order by owner = 'Jan' DESC 

答案 2 :(得分:0)

试试这个

SELECT * FROM cars where id not in (select id from cars where owner='Jan' and id = 9) order by owner = 'Jan' desc;