我如何从不同的桌面上网?
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
答案 0 :(得分:0)
如果每个用户有一个表,那么您可以以编程方式创建一个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)