首页 > 解决方案 > 使用 IF 条件运行 sql 查询时出错

问题描述

运行查询时出现错误

INSERT INTO `received_order`(
    `retailer_name`,
    `order_id`,
    `dboy_username`,
    `product_id`,
    `quantity`,
    `create_date`,
    `timestamp`,
    `payment_status`,
    `delivery_status`,
    `device_type`
)
VALUES(
    'ankur',
    'OD123',
    'manish',
    'PIDEAB565',
    (
    SELECT
        `product_quantity` IF(product_quantity > 50, 50, 0)
    FROM
        `master_stock`
    WHERE
        `product_id` = 'PIDEAB565'
),
'',
'',
'',
'',
''
)

MySQL 说:

1064 - 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以 master_stock 在第 20 行的 'IF(product_quantity 50, 50, 0) FROM WHERE'附近使用正确的语法

标签: sqlmariadb

解决方案


inline product_quantity IF(product_quantity > 50, 50, 0)IF 不能这样使用。您应该改用case语句。

尝试这个

INSERT INTO `received_order`(
    `retailer_name`,
    `order_id`,
    `dboy_username`,
    `product_id`,
    `quantity`,
    `create_date`,
    `timestamp`,
    `payment_status`,
    `delivery_status`,
    `device_type`
)
VALUES(
    'ankur',
    'OD123',
    'manish',
    'PIDEAB565',
    (
    SELECT
        case when `product_quantity`>50 then 50 else 0 end
    FROM
        `master_stock`
    WHERE
        `product_id` = 'PIDEAB565'
),
'',
'',
'',
'',
''
)

推荐阅读