SQL 中是否有更好的 CASE 替代方案?

时间:2021-02-05 12:08:12

标签: mysql sql case

我正在处理以下 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');

1 个答案:

答案 0 :(得分:0)

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

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

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

相关问题