[英]How to order by custom rule, e.g. how to order like 4,2,1,3
I am not sure that the title is saying it right, most probably it does not :) 我不确定标题是否说得对,很可能不是:)
So I have products
table and I want to order them by the season they are made for. 所以我有
products
表,我想在他们制作的季节订购。
If 'spring' is 1, 'summer' - 2 , 'autumn' - 3 and 'winter' - 4, how can I order them in such way so it shows the 'summer' first, then 'spring', then 'winter' and at the end 'autumn'. 如果'spring'是1,'summer' - 2,'autumn' - 3和'winter' - 4,我怎样才能以这样的方式订购它们以便首先显示'summer',然后是'spring',然后是'winter' '并在'秋天'结束。 So like 2,1,4,3.
就像2,1,4,3一样。
And to clarify it more, I want to be able to change the rule. 为了更清楚地说明,我希望能够改变规则。 It might be 2,1,4,3 or 4,2,1,3, etc. This is to show the season products on top.
可能是2,1,4,3或4,2,1,3等。这是为了展示季节产品。
Hope that explanation helps to get the problem. 希望解释有助于解决问题。 Any solutions are welcomed.
欢迎任何解决方案。 Database is MySQL, language PHP.
数据库是MySQL,语言PHP。
This should work for all major dbms: 这适用于所有主要的dbms:
order
by case when season = 2 then 1
when season = 1 then 2
when season = 4 then 3
when season = 3 then 4
end;
You could also add a column to your season table to indicate how they should be sorted: 您还可以在季节表中添加一列,以指示它们应如何排序:
table season(
season_id int
,ordinal int
);
select ...
from tab t
join seasons s on(t.season_id = s.season_id)
order
by s.ordinal;
...or, if you feel like writing non-portable code you can use: ...或者,如果您想编写非可移植代码,您可以使用:
order by field(season_id, 2,1,4,3);
Create a string of "season" ids. 创建一串“季节”ID。 Then do the order by field thing:
然后按字段顺序执行:
SELECT * FROM foo ORDER BY FIELD(season_id, 4, 2, 1, 3);
Replace the 4, 2, 1, 3 part with interpolated php variable. 用插值的php变量替换4,2,1,3部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.