如何编写子查询以动态地从未确定的表中获取相同的字段

Posted

技术标签:

【中文标题】如何编写子查询以动态地从未确定的表中获取相同的字段【英文标题】:How to write subquery to get the same fields from undetermined tables dynamically 【发布时间】:2021-12-29 04:42:59 【问题描述】:
SELECT SUM(t.orgBilledDuration/60) AS Duration
FROM 
(SELECT orgBilledDuration FROM Successfuliptsp.vbSuccessfulCDR_631
     WHERE FROM_UNIXTIME(connectTime/1000, '%Y-%m-%d %H:%i:%s') BETWEEN '2021-10-20 00:00:00' AND '2021-12-05 23:59:59'
 UNION ALL
 SELECT orgBilledDuration FROM Successfuliptsp.vbSuccessfulCDR_632
     WHERE FROM_UNIXTIME(connectTime/1000, '%Y-%m-%d %H:%i:%s') BETWEEN '2021-10-20 00:00:00' AND '2021-12-05 23:59:59'
 UNION ALL
 SELECT orgBilledDuration FROM Successfuliptsp.vbSuccessfulCDR_633
     WHERE FROM_UNIXTIME(connectTime/1000, '%Y-%m-%d %H:%i:%s') BETWEEN '2021-10-20 00:00:00' AND '2021-12-05 23:59:59'
) t

从上面的 SQL 中,我尝试编写以下查询来动态地从未确定的表中选择相同的字段。以下查询动态给出一张表的结果,但需要动态编写上述子查询。有人可以就此提出建议吗?

每个嵌套的 select 语句都适用于按月计算的表。需要从不同月份的表中搜索

SET @tab_id:= 631;
SET @tab:= concat('Successfuliptsp.vbSuccessfulCDR_',@tab_id);
SET @ID_1:= 'FROM_UNIXTIME(connectTime/1000, ''%Y-%m-%d %H:%i:%s'') BETWEEN ''2021-11-25 00:00:00'' AND ''2021-11-30 23:59:59''';
SET @s = CONCAT('select SUM(orgBilledDuration)/60 from ', @tab, ' where ', @ID_1); 
PREPARE STMT1 FROM @s; 
EXECUTE STMT1; 
DEALLOCATE PREPARE STMT1;

【问题讨论】:

【参考方案1】:
SET @s1:='SELECT SUM(t.orgBilledDuration/60) AS Duration FROM (';
SET @s2:='SELECT orgBilledDuration FROM Successfuliptsp.vbSuccessfulCDR_';
SET @s3:=' WHERE FROM_UNIXTIME(connectTime/1000, ''%Y-%m-%d'') BETWEEN ''2021-10-20'' AND ''2021-12-05''';
SET @s4:=') t';

SELECT CONCAT(@s1,
              GROUP_CONCAT(CONCAT(@s2,
                                  numbers.tab_no,
                                  @s3)
                           SEPARATOR ' UNION ALL '),
              @s4)
INTO @s
FROM ( SELECT 631 tab_no UNION ALL
       SELECT 632 UNION ALL
       SELECT 633 ) numbers;

PREPARE stmt FROM @s; 
EXECUTE stmt; 
DROP PREPARE stmt;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=ee5e3a98a43d70443135ce76bee56d74

【讨论】:

以上是关于如何编写子查询以动态地从未确定的表中获取相同的字段的主要内容,如果未能解决你的问题,请参考以下文章

THINKPHP如何获取一个表2个字段中相同的数据

如何基于字段查询具有单个子对象的表中的对象的sql?

MySQL 从两个不同的表中获取 user_id 和密码的查询

MySQL学习——SQL查询语句(连接查询&子查询)

如何优化限制查询以更快地从大表中访问数据?

如何高效地从多个表中查询子记录?