【发布时间】:2020-06-30 07:18:55
【问题描述】:
在这种情况下MySQL pivot row into dynamic number of columns 几乎是相同的情况,但结果不同,这让我感到困惑。
假设我有 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
所以就像MySQL pivot row into dynamic number of columns 中的前一个案例一样,我想在 order_status_id 中输入产品名称而不是 7 中的交易(因为 7 是过期交易并被拒绝)
the expected results was like this :
id (in order_match) | Orange | Carrot | Apple
1 1 0 0
3 1 0 0
4 1 0 1
基于之前案例的解决方案,我使用了这个
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;
但是我想知道为什么返回 0 是不可能的
【问题讨论】:
-
正如已经不止一次提到的那样:meta.stackoverflow.com/questions/333952/…。也就是说,您最好的选择(同样如前所述)是处理应用程序代码中的数据显示问题
-
对不起先生,先生,@Strawberry 先生
-
将
SELECT @sql;添加到您的小提琴中。执行。然后复制它的FROM部分,添加SELECT *并执行。调查结果。 -
idk 为什么返回 0 因为
sales中没有 partner_id=2 和 product_id=1 的行。 -
对不起先生,这是错误的小提琴