【问题标题】:Select rows in MySQL table with specific or default value在 MySQL 表中选择具有特定值或默认值的行
【发布时间】:2019-01-29 03:01:18
【问题描述】:

我是新来的,如果这是一个愚蠢的问题,我很抱歉。我需要有关 mysql 查询的帮助。

我们为客户提供各种服务。我们的服务和价格都在这样的表格中

service    | customer    | price
  1        |     0       | 1.1 
  2        |     0       | 2.1 
  3        |     0       | 1.3
  2        |     1       | 1.9 
  3        |     2       | 1.2 

如果客户 = 0,则为默认价格。如果客户 > 0,那么它是该服务的客户特定价格。

我们需要向个人客户显示所有服务的价格。因此,我们需要查询,如果存在客户特定价格,则显示其他默认价格。

所以对于客户 1,它应该显示

service    | customer    | price
  1        |     0       | 1.1 
  2        |     1       | 1.9 
  3        |     0       | 1.3

对于客户 2,它应该显示

service    | customer    | price
  1        |     0       | 1.1 
  2        |     0       | 2.1 
  3        |     2       | 1.2 

对于任何其他客户,

service    | customer    | price
  1        |     0       | 1.1 
  2        |     0       | 2.1 
  3        |     0       | 1.3

我尝试过

select service, customer, price from services where (customer=1 or customer = 0) order by customer desc

但它不会产生所需的输出

【问题讨论】:

    标签: mysql select


    【解决方案1】:

    您可以通过使用客户 1(或您想要的任何客户)的值对客户 0 的价格进行自我 JOIN,在 service 上使用 LEFT JOIN 并替换任何 @ 来获得所需的结果987654325@ 值为客户 0 的价格:

    SELECT s0.service,
           COALESCE(s.price, s0.price) AS price
    FROM (SELECT service, price
          FROM services
          WHERE customer = 0) s0
    LEFT JOIN services s ON s.service = s0.service AND s.customer = 1
    ORDER BY service
    

    输出(customer = 1):

    service     price
    1           1.10
    2           1.90
    3           1.30
    

    Demo on dbfiddle(还显示customer = 2customer = 3 的结果)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 2011-03-06
      相关资源
      最近更新 更多