比如 有这些表
tbl_100
tbl_103
tbl_97
tbl_16
tbl_29
tbl_99
...只知道表名是tbl前缀,但是想 union多个表的查询结果怎么写sql语句啊??
例如
select sum(pn) from (
select count(*) pn from tbl_??? union 
select count(*) pn from tbl_??? union 
...
select count(*) pn from tbl_???)tmp_tbl;google了下似乎找不到答案请高手们指点指点

解决方案 »

  1.   

    prepare...
    execute ...
    drop prepare...
      

  2.   

    要动态生成SQL语句?
    先取得所有以TBL开关的表名,再循环、字符累加形成SQL语句,执行sELECT table_name, table_type, engine
         FROM information_schema.tables
         WHERE table_schema = 'DATABASE' AND table_name LIKE 'tbl_%'
      

  3.   


    delimiter //
    create procedure getcount(in start int,in end int)
    begin
    declare tmp int;
    declare sqlstr text default '';
    set tmp = start;while tmp <= end do
    if tmp = end then
    set sqlstr = concat(sqlstr,'select count(*) pn from tbl_',tmp);
    else
    set sqlstr = concat(sqlstr,'select count(*) pn from tbl_',tmp,' union ');
    end if;
    set tmp = tmp + 1;
    end while;set @str = concat('select sum(pn) from(',sqlstr,')tmp');prepare stmt1 from @str;
    execute stmt1;
    deallocate prepare stmt1;
    end
    //
    delimiter ;
      

  4.   

    <?php
          connect database;
          $result=mysql_query("show tables from db_name like 'tbl_%'");
          foreach($result as $value){
                  $sql 连接
           }
          mysql_query("$sql");
    ?>