按条件下单

Putting order according to the condition

我有一个问题:

SELECT * FROM Cars WHERE (cars.mark = "Audi" and cars.model = "a4" and cars.year = 2008) or 
             (cars.mark = "Audi" and cars.model <> "a4" and cars.year = 2008) or  
             (cars.mark <> "Audi" and cars.model <> "a4" and cars.year = 2008 )

如何按条件订购。第一个结果:cars.mark = "Audi" and cars.model = "a4" and cars.year = 2008,下一个结果:(cars.mark = "Audi" and cars.model <> "a4" and cars.year = 2008),第三个:(cars.mark <> "Audi" and cars.model <> "a4" and cars.year = 2008 )

我不能使用联合查询,因为它是 Symfony 项目并且不支持联合。谢谢

不确定您的 where 条件是否有用,基本上它说给我所有标记 2008 年的模型,我很确定该模型在所有标记中都是独一无二的。至于结果的排序可以有条件地排序。

drop table if exists t;
create table t
(mark varchar(4) , model varchar(4), year int);

insert into t values
('audi','a3',2008),
('ford','st',2008),
('audi','a4',2008),
('gm','junk',2008),
('gm','junk',2009),
('ford','xx',2008);


SELECT * FROM t 
WHERE  year = 2008
order by 
case when t.mark = "Audi" and t.model = "a4"  then 1 
     when t.mark = "Audi" and t.model <> "a4"  then 2 
     when t.mark <> "Audi" and t.model <> "a4" then 3
     else 4
     end ,
mark desc;

+------+-------+------+
| mark | model | year |
+------+-------+------+
| audi | a4    | 2008 |
| audi | a3    | 2008 |
| gm   | junk  | 2008 |
| ford | st    | 2008 |
| ford | xx    | 2008 |
+------+-------+------+