【问题标题】:Mysql - select and order by two price columns as oneMysql - 按两个价格列作为一个选择和排序
【发布时间】:2016-08-25 14:37:52
【问题描述】:

我在从 mysql 中选择数据时遇到了一个问题,我无法弄清楚。尝试做研究,但没有运气。

我有 4 列的表格:

id | name | price | discount_price
1 | Test 1 | 150  | 50
4 | test 2 | 130  | 300
2 | test 3 | 200  | 0
3 | test 4 | 130  | 10
4 | test 5 | 80  | 0

我需要选择数据并按价格排序,如果 discount_price 不是“零”,则按 price_discount 排序。问题是,现在它没有像我预期的那样工作。它显示结果,因为第一列已排序,最后是第二列排序。取决于我选择 ASC 还是 DESC。

我需要实现类似将这两列合并为一列而不是排序。像这样:

id | name | price | discount_price
3 | test 4 | 130  | 10*
4 | test 5 | 80* | 0
1 | Test 1 | 150  | 50*
2 | test 3 | 200*  | 0
4 | test 2 | 130  | 300*

在mysql中可以吗?或者应该在 php 之后对此进行排序?感谢您的帮助。

【问题讨论】:

  • 10,80,50,200,300 没有多大意义(至少对我而言)。
  • 我有同样的问题,你可以如何进行不必要的排序。 10,80,50,200,300。这对我来说也没有任何意义。如果你想要 10,50,80,200,300。然后你可以从下面的查询中得到:Select id,name,price,discount_price, if(discount_price=0,price,discount_price) as sort_order FROM table order by sort_order ASC
  • 你昨天不是问过这个吗,没有人理解你的要求,问题被删除了
  • +1 表示if(discount_price=0,price,discount_price) as sort_order FROM table order by sort_order ASC。比我的回答更优雅。
  • 如果您使数据有意义,它可以帮助我们理解您的问题 您有一行具有比实际价格更大的 discount_price。 帮助我们为您提供帮助这只是让我们相信您已经冲到桌子上展示了您的要求

标签: php mysql sorting sql-order-by


【解决方案1】:

试试这个(建表中的字段定义是伪代码):

CREATE TEMPORARY TABLE sort (id INT, name VARCHAR, INT price, INT discount_price, INT actual_price) ;
INSERT INTO sort (id, name, price, discount_price)
    SELECT id, name, price, discount_price
    FROM original_table ;
UPDATE sort SET actual_price = price WHERE discount_price = 0 ;
UPDATE sort SET actual_price = discount_price WHERE discount_price != 0 ;
SELECT id, name, price, discount_price FROM sort ORDER BY actual_price ;

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 2012-12-21
    相关资源
    最近更新 更多