按与变量匹配的多列排序
我目前有这样的 mysql 语句:
SELECT * FROM tablename
WHERE column1 = 'yes'
ORDER BY
CASE column2 WHEN 'premium' THEN 1
WHEN 'basic' THEN 2
ELSE 999
END,
customer_id ASC
我想添加另一列......所以这就是我最终想要做的。
ORDER BY:
column2 = premium
THEN
column2 = basic
THEN
column3 = specialcustomer
THEN
display remaining results according to customer_id ASC
所以输出是按照我希望它出现的顺序排列的。
约翰·多伊 - 高级, 莎莉·琼斯 - 高级, 吉姆·史密斯 - 基本 - 特殊客户, 唐·约翰逊 - 基本 - 不是特殊客户, 玛丽·李 - 基本 - 非特殊客户
I currently have this mysql statement:
SELECT * FROM tablename
WHERE column1 = 'yes'
ORDER BY
CASE column2 WHEN 'premium' THEN 1
WHEN 'basic' THEN 2
ELSE 999
END,
customer_id ASC
I'd like to add another column to the mix....so here is what I would ultimately like to do.
ORDER BY:
column2 = premium
THEN
column2 = basic
THEN
column3 = specialcustomer
THEN
display remaining results according to customer_id ASC
So the output, in the order I would like it to appear.
John Doe - premium,
Sally Jones - premium,
Jim Smith - basic - specialcustomer,
Don Johnson - basic - notspecialcustomer,
Mary Lee - basic - notspecialcustomer
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
column3 = 'specialcustomer'
是应该返回true
如果specialcustomer 的检查。order by
部分发生的情况是您可以将其想象为 3 个额外的虚拟列,它们从这些表达式中获取各自的值:
1)
case ...
2)if ...
3)customer_id
然后数据行按这些列值按顺序排序。
column3 = 'specialcustomer'
is the check that should be returningtrue
if specialcustomer.What is going on in the
order by
section is thatyou can picture this like 3 additional virtual columns which get their respective value from these expressions:
1)
case ...
2)if ...
3)customer_id
And then rows of the data are sorted by these column values in order.