我有一个系统可以在子查询中生成带有大量派生表的SQL查询。这是一个典型的例子:
SELECT
COUNT(`temp_table_main`.`person_id`) AS "resp_count",
`temp_table_main`.`SAMPLE`,
SUM(`temp_table_main`.`WT`) AS "resp_count_weight" ,
SUM(`temp_table_main`.`field1`) as `field1_count`,
(
SELECT
SUM(`temp_table_field1`.`WT`)
FROM
(
SELECT
`person_id`,
MAX(CASE when `variable` = 4 THEN `value` END) AS `field1`,
MAX(CASE when `variable` = 10 THEN `value` END) AS `WT`,
MAX(CASE when `variable` = 3 THEN `value` END) AS `SAMPLE`
FROM
`4_86_data`
GROUP BY `person_id`
) AS `temp_table_field1`
WHERE `temp_table_field1`.`field1` = 1
AND `SAMPLE` = `temp_table_main`.`SAMPLE`
) AS `field1_count_WT`
FROM
(
SELECT
`person_id`,
MAX(CASE when `variable` = 4 THEN `value` END) AS `field1` ,
MAX(CASE when `variable` = 3 THEN `value` END) AS `SAMPLE` ,
MAX(CASE when `variable` = 10 THEN `value` END) AS `WT`
FROM
`4_86_data`
GROUP by `person_id`
) AS `temp_table_main`
WHERE ( `field1` IS NOT NULL ) GROUP BY `SAMPLE`
我想做的是能够将其格式化为:
SELECT
COUNT(`temp_table_main`.`person_id`) AS "resp_count",
`temp_table_main`.`SAMPLE`,
SUM(`temp_table_main`.`WT`) AS "resp_count_weight" ,
SUM(`temp_table_main`.`field1`) as `field1_count`,
(
SELECT
SUM(`temp_table_field1`.`WT`)
FROM
`temp_table_main` AS `temp_table_field1`
WHERE `temp_table_field1`.`field1` = 1
AND `SAMPLE` = `temp_table_main`.`SAMPLE`
) AS `field1_count_WT`
FROM
(
SELECT
`person_id`,
MAX(CASE when `variable` = 4 THEN `value` END) AS `field1` ,
MAX(CASE when `variable` = 3 THEN `value` END) AS `SAMPLE` ,
MAX(CASE when `variable` = 10 THEN `value` END) AS `WT`
FROM
`4_86_data`
GROUP by `person_id`
) AS `temp_table_main`
WHERE ( `field1` IS NOT NULL ) GROUP BY `SAMPLE`
您会注意到我试图在外部select语句的子查询中引用外部派生表,并将其分配给temp_table_field1
。
在某些情况下,我会在外部select语句中包含N个这样的子查询,因此需要将其指定为不同的派生表名。
也许这个问题是,我可以从派生表派生一个表吗?
顺便说一下,我的sql通过拥有大量的派生表来运行并执行得很好,我只是想知道是否:另请注意:我不能将这些分配为临时表。它必须在一个查询中执行。