在MySQL数据库中,我正在寻求从符合条件的字段创建列。
这有效:
DROP TABLE IF EXISTS report4;
create TABLE report4 as (
select
orders_products.orders_id,
MAX( IF(products_id = 1, final_price, "-") ) AS Membership,
MAX( IF(products_id = 12, final_price, "-" ) ) AS Donation,
MAX( IF( products_id = 16, final_price, "-" ) ) AS AHCD
from orders_products
Group by orders_id M);
select * from report4;
但我还有其他product_id,我希望注入会员和捐赠的新栏目。
ID为2,3,4,5,6,7,8,9,10,11的产品将进入会员资格。 ID为13,14,15,17,18的产品将进入捐赠。
这是次要部分我无法开展工作。关于我需要做什么的想法。
答案 0 :(得分:0)
使用以下语法:
MAX( IF(products_id IN (2,3,4,5,6,7,8,9,10,11), final_price, "-") )
答案 1 :(得分:0)
将内部查询更改为products_id IN (....)
,如下所示
DROP TABLE IF EXISTS report4;
create TABLE report4 as ( select
orders_products.orders_id,
MAX( IF(products_id IN ( 1,2,3,4,5,6,7,8,9,10,11 ), final_price, "-") ) AS Membership,
MAX( IF(products_id IN ( 12,13,14,15,17,18 ), final_price, "-" ) ) AS Donation,
MAX( IF( products_id = 16, final_price, "-" ) ) AS AHCD
from orders_products
Group by orders_id M);
select * from report4;
或者,您也可以使用products_id = 1 OR products_id = 2 OR ...
代替IN
答案 2 :(得分:0)
@Lobo的答案适用于您所寻找的内容。但是,如果您必须添加更多产品,则必须不断重做查询,并且它不可扩展。您应该更改数据库以在某处存储 products_type 列,这样您就可以在需要时对产品进行简单的重新分类,并使查询每次都正确运行。
添加一个名为products_types
的表格,您可以改为使用此查询:
select
orders_products.orders_id,
MAX( IF(pt.types_id = 1, final_price, "-") ) AS Membership,
MAX( IF(pt.types_id = 2, final_price, "-" ) ) AS Donation,
MAX( IF(pt.types_id = 3, final_price, "-" ) ) AS AHCD
from orders_products
join products_types pt on (pt.products_id = orders_products.products_id)
group by orders_id
我使用的类型的表定义是:
CREATE TABLE `products_types` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`products_id` int(11) DEFAULT NULL,
`types_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;