【发布时间】:2020-07-07 08:40:56
【问题描述】:
我有 3 个这样的表
create table order_match
(
id int(10) PRIMARY KEY not null,
order_status_id int(10) not null
);
create table order_match_detail
(
id int(10) PRIMARY KEY not null,
order_match_id int(10) not null,
product_id int(10) NOT NULL
);
create table product
(
id int(10) PRIMARY KEY not null,
name varchar(255) not null
);
Insert into order_match (id, order_status_id)
select 1, 6 union all
select 2, 7 union all
select 3, 6 union all
select 4, 6;
Insert into order_match_detail (id, order_match_id, product_id)
select 1, 1, 147 union all
select 2, 2, 148 union all
select 3, 3, 147 union all
select 4, 4, 149 union all
select 5, 4, 147;
Insert into product (id, name)
select 147, 'orange' union all
select 148, 'carrot' union all
select 149, 'Apple';
order_match.id = order_match_detail.order_match_id
和order_match_detail.product_id = product.id
我想将order_status_id 不在 7 中的数据设为成功交易,从该成功交易开始,如果交易购买苹果,则苹果的列包含 1 否则如果不购买,则 0这是我的预期结果,我想将这些数据用于分析
id (in order_match) | Orange | Carrot | Apple
1 1 0 0
3 1 0 0
4 1 0 1
这个问题我可以用这个查询来解决
select om.id,
count(DISTINCT case when omd.product_id = 147 THEN 1 END) Orange,
count(DISTINCT case when omd.product_id = 148 THEN 1 END) Carrot,
count(DISTINCT case when omd.product_id = 149 THEN 1 END) Apple
from order_match om
left join order_match_detail omd
on om.id = omd.order_match_id
where om.order_status_id in (4, 5, 6, 8)
group by om.id
真正的问题是,在我的真实数据库中,它包含 1550 product_id,如何使其自动生成,因此无需手动输入 product_id 直到 1550 product_id
这是小提琴https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=c0eb7fe1b012ab1c909d37e325a8d434
我已经尝试过这样的新查询,但仍然错误
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'count(case when product.name = ''',
product.name,
''' then 1 end) AS ',
replace(product.name, ' ', '')
)
) INTO @sql
from product;
SET @sql = CONCAT('SELECT omd.order_match_id, ', @sql, ' from order_match_detail omd
left join order_match om
on omd.order_match_id = om.id
left join product p
on omd.product_id = p.id
where om.order_status_id in (4, 5, 6, 8)
group by omd.order_match_id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
【问题讨论】:
-
您打算有 1550 列吗?
-
我们可以在存储过程中使用游标
-
是的,先生,没问题,因为我想用另一个数据挖掘软件@tcadidot0 来分析它
-
你能给我一个关于存储过程的建议吗@SivaKoteswaraRao
-
所有那些product_id 都是从1 到1550 的编号?另外,您使用的是什么 MySQL/MariaDB 版本?