我正在尝试在MySQL中创建以下伪代码。我有以下表格:
product_filter
表只有两列,product_id
和filter_id
我想提出一个SQL:
specials
表中读取所有product_id并将其放入product_filter
表specials
表中读取产品ID时,还需要查看price
列这是我到目前为止所做的:
INSERT INTO product_filter (product_id,filter_id)
SELECT product_id,
FROM specials;
感谢任何帮助。
答案 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;