我有以下几个描述的关系表:
alpha_codes
beta_codes
实体
beta_codes_entities
我想问的是,如果我可以选择GROUP BY BY alpha_code和beta_code的数量的和,从而产生以下二维数组:
+------------+---------------+---------------+---------------+---------------+
| | betacode1 | betacode2 | ... | betacodeN |
+------------+---------------+---------------+---------------+---------------+
| alphacode1 | SUM(quantity) | SUM(quantity) | ... | SUM(quantity) |
+------------+---------------+---------------+---------------+---------------+
| alphacode2 | SUM(quantity) | SUM(quantity) | ... | SUM(quantity) |
+------------+---------------+---------------+---------------+---------------+
| ... | ... | ... | ... | SUM(quantity) |
+------------+---------------+---------------+---------------+---------------+
| alphacodeN | SUM(quantity) | SUM(quantity) | SUM(quantity) | SUM(quantity) |
+------------+---------------+---------------+---------------+---------------+
到目前为止,我有以下简单查询,虽然它返回所有必需的数据,但结果集格式不同,需要手动重组才能构建上表所示的二维数组。
SELECT
`alpha_codes`.`code` as alphacode,
`beta_codes`.`code` as betacode,
SUM(`entities`.`quantity`)
FROM
`entities`
INNER JOIN
`alpha_codes` ON `alpha_codes`.`id` = `entities`.`alpha_code_id`
INNER JOIN
`beta_code_entity` ON `beta_code_entity`.`entity_id` = `entities`.`id`
INNER JOIN
`beta_codes` ON `beta_codes`.`id` = `beta_code_entity`.`beta_code_id`
GROUP BY `alpha_codes`.`id` , `beta_codes`.`id`
输出
+------------+---------------+------------------------+
| alphacode | betacode | SUM(entities.quantity) |
+------------+---------------+------------------------+
| alphacode1 | betacode1 | SUM(entities.quantity) |
+------------+---------------+------------------------+
| alphacode1 | betacode2 | SUM(entities.quantity) |
+------------+---------------+------------------------+
| alphacode2 | betacode1 | SUM(entities.quantity) |
+------------+---------------+------------------------+
| ... | ... | ... |
+------------+---------------+------------------------+
| alphacodeN | SUM(quantity) | SUM(quantity) |
+------------+---------------+------------------------+
如果有少量固定数量的betacodes,我正考虑为每一个使用多个CASE语句。然而,现实世界的场景包括大约850个字母代码,1000个betacode和超过500k个实体,因此我也非常担心性能问题...
答案 0 :(得分:0)
在下面的解决方案中: 必须动态生成SQL语句。 和短语列表(带有.....的部分)必须通过循环通过betacode值生成。您可以将Case语句放入函数中,同时将两个参数发送到函数。
由于您已经处于必须构建N列的情况,N先前不知道但仅在运行时已知,因此基于betacode的值动态构建SUM短语不应该有很大差异/难。
eval $(grape resolve -shell javax.servlet javax.servlet-api 4.0.0)
另一种解决方案是:
一个。创建一个包含输出列的临时表。如果单个表的列太多,创建多个列,就像表分区一样,您可以稍后加入它们。
湾循环记录。从实体表或betacodes开始。在循环内写入Update语句,它将从您已发布的查询中提取值。如果循环通过betacode列,您将一次为所有实体更新一列。