从未知表名中选择

30byixjq  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(302)

如何从不同的table上网?

SELECT count(online) FROM (SELECT UserTableName FROM `name`) WHERE online = 1

--------------
UserTableName
--------------
users_1
users_2
users_3

--------------
users_x
--------------
1
0
0
1

我需要从不同的表中获取联机和表名示例:

-----------------
 online | table
-----------------
       5| users_1
       3| users_2
       9| users_3
mcvgt66p

mcvgt66p1#

如果每个用户有一个表,那么可以通过编程方式创建一个sql语句(从链接表中获取不同的表名并将它们联合起来),然后提交。https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html
举个例子

MariaDB [sandbox]> select id,username from users where id < 3;
+----+----------+
| id | username |
+----+----------+
|  1 | John     |
|  2 | Jane     |
+----+----------+
2 rows in set (0.00 sec)

MariaDB [sandbox]> select * from john;
+--------+
| online |
+--------+
|      1 |
|      0 |
+--------+
2 rows in set (0.00 sec)

MariaDB [sandbox]> select * from jane;
+--------+
| online |
+--------+
|      1 |
|      1 |
+--------+
2 rows in set (0.00 sec)

此代码

SET @SQL =
( 
SELECT  GROUP_CONCAT(GCSTRING)
FROM
(
SELECT 'A' AS GC,CONCAT(sstring,name,fstring, usertable,ustring) gcstring
FROM
(
SELECT DISTINCT 'select count(*) as online # ' as sstring, concat(char(39),username,char(39)) as name, 
' as user from ' as fstring, username AS usertable, ' Where online = 1  UNION '  as USTRING from users where id < 3
) S
) T
GROUP BY GC
)
;

SET @SQL = REPLACE(@SQL,',',' ');
SET @SQL = REPLACE(@SQL,'#',',');
SET @SQL = SUBSTRING(@SQL,1,LENGTH(@SQL) - 6);
SET @SQL = CONCAT(@SQL,';');

# SELECT @SQL;

prepare stmt1 from @sql;
execute stmt1;
deallocate prepare stmt1;

生成此结果

+--------+------+
| online | user |
+--------+------+
|      1 | John |
|      2 | Jane |
+--------+------+
2 rows in set (0.00 sec)

相关问题