0

从 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 注入到 Membership 和 Donation 的新列中。

ID 为 2、3、4、5、6、7、8、9、10、11 的产品将成为会员。ID 为 13、14、15、17、18 的产品将进入捐赠模式。

这是我无法完成的次要部分。关于我需要做什么的想法。

4

3 回答 3

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

于 2013-09-12T04:15:09.037 回答
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;
于 2013-09-12T07:15:46.950 回答
0

使用此语法:

MAX( IF(products_id IN (2,3,4,5,6,7,8,9,10,11), final_price, "-") ) 
于 2013-09-12T04:14:19.880 回答