按与变量匹配的多列排序

发布于 2024-11-28 07:20:48 字数 578 浏览 0 评论 0原文

我目前有这样的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

守护在此方 2024-12-05 07:20:48
SELECT * FROM tablename
 WHERE column1 = 'yes'
 ORDER BY
       CASE column2 WHEN 'premium' THEN 1
                    WHEN 'basic' THEN 2
                    ELSE 999
       END,
       IF(column3 = 'specialcustomer', 1, 2),
       customer_id ASC

column3 = 'specialcustomer' 是应该返回 true 如果specialcustomer 的检查。

order by 部分发生的情况是
您可以将其想象为 3 个额外的虚拟列,它们从这些表达式中获取各自的值:
1) case ... 2) if ... 3) customer_id

然后数据行按这些列值按顺序排序。

SELECT * FROM tablename
 WHERE column1 = 'yes'
 ORDER BY
       CASE column2 WHEN 'premium' THEN 1
                    WHEN 'basic' THEN 2
                    ELSE 999
       END,
       IF(column3 = 'specialcustomer', 1, 2),
       customer_id ASC

column3 = 'specialcustomer' is the check that should be returning true if specialcustomer.

What is going on in the order by section is that
you 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文