MySql:在复杂的if语句中更改源表

时间:2014-04-03 17:17:23

标签: mysql sql opencart

我不确定这是否可行。但我有以下sql根据产品的特殊价格将一些值插入product_filter表。

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
  WHEN price >= 1000 AND price < 1500 then 4
  WHEN price >= 1500 AND price < 2000 then 5
  WHEN price >= 2000 AND price < 2500 then 50
  WHEN price >= 2500 AND price < 3000 then 6
  ELSE 51 END) AS filter_id
FROM product_special;

我想修改上面的脚本,这样如果没有为产品设置特殊价格,它只会从主product表中读取常规价格。由于这将在一个大型产品数据库上运行,我希望可能结合两个脚本而不是我在某些产品上手动运行不同的脚本。

感谢您的帮助。

1 个答案:

答案 0 :(得分: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
  WHEN price >= 1000 AND price < 1500 then 4
  WHEN price >= 1500 AND price < 2000 then 5
  WHEN price >= 2000 AND price < 2500 then 50
  WHEN price >= 2500 AND price < 3000 then 6
  ELSE 51 END) AS filter_id
  FROM product_special
  union
  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
  WHEN price >= 1000 AND price < 1500 then 4
  WHEN price >= 1500 AND price < 2000 then 5
  WHEN price >= 2000 AND price < 2500 then 50
  WHEN price >= 2500 AND price < 3000 then 6
  ELSE 51 END) AS filter_id
  FROM product where product_id not in
  (select product_id from product_special)

以上查询假定您在product_id表格中有priceproduct(作为标准/常规价格)列。这里的想法是从product_special表中获取所有现有产品及其特殊价格,并在其中添加product_special表中不存在的产品,但是在product表中以及标准/常规价格