【问题标题】:Is there a better alternative to CASE in SQL?SQL 中是否有更好的 CASE 替代方案?
【发布时间】:2021-02-05 12:08:12
【问题描述】:

我正在处理以下 SQL 查询(见下文)。有没有更好的方法来处理条件列“shipment_type”?我可能要添加更多条件,并且一遍又一遍地重复同一行的想法对我来说效率很低。有什么建议吗?

SELECT
    u.user_id,
    u.user_email,
    o.order_id,
    o.product,
    o.amount,
    s.shipment_method,
    s.shipment_date,
    CASE
        WHEN s.shipment_comment LIKE '%international%' THEN 'international'
        WHEN s.shipment_comment LIKE '%worldwide%' THEN 'international'
        WHEN s.shipment_comment LIKE '%global%' THEN 'international'
        -- more conditions
        ELSE 'national'
    END AS shipment_type
FROM users AS u
    JOIN orders AS o 
        ON u.user_id = o.user_id
    JOIN shipments AS s
        ON s.order_id = o.order_id
WHERE
    u.country IN ('US', 'UK');

【问题讨论】:

  • 我删除了不一致的数据库标签。
  • 您使用的是哪个 dbms?
  • 我目前正在使用 MySQL。

标签: mysql sql case


【解决方案1】:

您可以使用正则表达式。在 MySQL 中,这看起来像:

(CASE WHEN s.shipment_comment regexp 'international|worldwide|global'
      THEN 'international'
      -- more conditions
      ELSE 'national'
 END) AS shipment_type

Postgres 具有类似的功能,但使用 ~ 而不是 REGEXP

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多