仅当满足特定条件时,才从另一个表中插入表值

时间:2014-02-17 18:18:47

标签: mysql sql opencart

我正在尝试在MySQL中创建以下伪代码。我有以下表格:

  • 特别
  • product_filter

product_filter表只有两列,product_idfilter_id

我想提出一个SQL:

  1. specials表中读取所有product_id并将其放入product_filter
  2. specials表中读取产品ID时,还需要查看price
  3. 如果价格低于100美元,过滤器ID将为1
  4. 如果价格介于$ 100和$ 500之间,则过滤器ID为2
  5. 如果价格介于$ 500和$ 1000之间,则过滤器ID将为3
  6. 这是我到目前为止所做的:

    INSERT INTO product_filter (product_id,filter_id)
    SELECT product_id, 
    FROM specials;
    

    感谢任何帮助。

4 个答案:

答案 0 :(得分:1)

尝试使用CASE来确定filter_id是什么(这将设置在这些边界中没有价格等于0的任何内容):

INSERT INTO product_filter (product_id,filter_id)
SELECT product_id,
    (CASE WHEN price < 100 then 1
    WHEN price >= 100 AND price < 500 then 2
    WHEN price >= 500 AND price < 1000 then 3
    ELSE 0 END) AS filter_id
FROM specials;

这是一个有效的SQLFiddle

答案 1 :(得分:0)

尝试此查询(您未指定高于1000的值,因此如果值大于1000,则会使filter_id为4。)

INSERT INTO product_filter (product_id,filter_id)
SELECT product_id,
       CASE WHEN price < 100 THEN 1
            WHEN price BETWEEN 100 AND 500 THEN 2
            WHEN price BETWEEN 500 AND 1000 THEN 3
            ELSE 4
       END as filter_id
FROM specials;

答案 2 :(得分:0)

使用类似的东西:

INSERT INTO product_filter (product_id,filter_id)
SELECT
  product_id, 
  (CASE
       WHEN price < 100 THEN 1 
       WHEN price BETWEEN 100 AND 500 THEN 2
       WHEN price BETWEEN 500 AND 1000 THEN 3
   END) as filter_id
 FROM specials;

答案 3 :(得分:0)

试试这个:

您还需要在子句范围值之间进行微小更改,如下所示:

INSERT INTO product_filter (product_id,filter_id)
SELECT product_id, 
       case when price < 100 then 1 -- price under $100, the filter id be 1
            -- price between $100 and $500, the filter id be 2
            when price between 101 and 500 then 2
            -- price between $500 and $1000, the filter id be 3
            when price between 501 and 1000 then 3
            -- else ? -- fill this as you need
FROM specials;