在mysql中使用pivot函数生成apriori表

mpbci0fu  于 2021-08-01  发布在  Java
关注(0)|答案(1)|浏览(299)

这与mysql将行透视成动态列数的情况几乎相同,但结果不同,这使我感到困惑。
假设我有三张table

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中的情况一样,将行转换为动态的列数,我想输入产品名称,并且事务的顺序是\u status\u id not in 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;

但是idk为什么返回0,这是不可能的
这是小提琴https://www.db-fiddle.com/f/nde3oq3vdtfs5qdokiehn4/6

myss37ts

myss37ts1#

对于您的群\u concat查询;在您的示例stmt中,您将产品表引用为 product 它自己。但在join查询中,将product表作为别名引用 p . 因为第一个groupconcat查询是join查询的一部分,所以需要保持表别名不变

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'count(case when p.name = ''',  
      product.name,
      ''' then 1 end) AS ',
      replace(product.name, ' ', '')
    )
  ) INTO @pivotsql
from product;

SET @sql = CONCAT('SELECT omd.order_match_id, ', @pivotsql, ' 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;

相关问题