INFORMATION_SCHEMA
,這樣你可以在一個查詢中瞭解(對於MySQL實例中的所有表格)哪些表格有一個active
列,然後使用這些資訊來建立你的查詢語句。這可能是最明智的方法。
還有一種棘手的方式,不管該表是否具有此類列,它都有效:
SELECT
( SELECT COUNT(*)
FROM TableName AS t
WHERE active = 1
) AS cnt
FROM
( SELECT 1 AS active
) AS dummy ;
在SQL-Fiddle上进行了测试。它是如何工作的?
如果表中有一个名为active
的列,查询将被“翻译”为具有该列的查询。
WHERE t.active = 1
如果表格中没有名为active
的列,查询将被“翻译”为具有该列的查询。
WHERE dummy.active = 1 -- which is true
使用仅限于users
表的UserID客户总数统计:
SELECT
IFNULL(u.id,'Total') UserID,
COUNT(u.clientid) ClientCount
FROM users u
WHERE u.active = 1
GROUP BY u.id WITH ROLLUP;
如果客户表中有已删除的记录,则执行以下操作:
SELECT
IFNULL(u.id,'Total') UserID,
COUNT(c.id) ClientCount
FROM users u INNER JOIN clients c
ON u.clientid = c.id
WHERE u.active = 1
GROUP BY u.id WITH ROLLUP;
对于没有active
列的users
表:
SELECT
IFNULL(u.id,'Total') UserID,
COUNT(u.clientid) ClientCount
FROM users u
GROUP BY u.id WITH ROLLUP;
或者
SELECT
IFNULL(u.id,'Total') UserID,
COUNT(c.id) ClientCount
FROM users u INNER JOIN clients c
ON u.clientid = c.id
GROUP BY u.id WITH ROLLUP;
你需要对每个数据库运行这些查询,并将结果使用UNION ALL
合并。
如果你想利用INFORMATION_SCHEMA数据库,那么这只是一个猜测:
SELECT COUNT(1) INTO @hasactive
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'users'
AND column_name = 'active';
SELECT
IFNULL(u.id,'Total') UserID,
COUNT(u.clientid) ClientCount
FROM users u
WHERE IF(@hasactive=1,u.active=1,1)=1
GROUP BY u.id WITH ROLLUP;
试一试吧!
SELECT
( SELECT
max(ISNULL(updateTime, null)) + max(ISNULL(updDT, null))
FROM tableName as t
) AS maxUpdateDT
FROM (SELECT 0 AS updateTime, 0 as updDT) AS dummy;