如何在一个查询中获取2个不同表(和数据库)的行数?

时间:2012-01-13 14:52:51

标签: mysql count rows

我在这个数据库里面有一个名为accountsaccount的数据库,另外我在这个数据库里面得到了一个名为playersplayer的数据库。

如何在一个查询中获取这两个表的行数?

我试过这个:

SELECT
    SUM(`account`.`account`.`id`) AS 'accounts',
    SUM(`player`.`player`) AS 'players';

但它不起作用。

5 个答案:

答案 0 :(得分:2)

对两个select语句执行简单的UNION操作:

SELECT COUNT(*), 'Accounts' FROM Accounts.Account
UNION
SELECT COUNT(*), 'Players' FROM Players.Player

并且您必须使用数据库名称限定每个表,因为它们位于不同的数据库中。

答案 1 :(得分:2)

如果您需要精确的行数(而不是总和),请执行以下操作:

select
(select count(*) from accounts.account) as count1,
(select count(*) from players.player) as count2

select count(*) as `count`,"account" as `table` from accounts.account
union all
select count(*) as `count`,"player" as `table` from players.player

答案 2 :(得分:1)

尝试:

SELECT
   COUNT(`account`.`id`) AS 'accounts',
   COUNT(`player`.`player`) AS 'players'
FROM
   `account`,
   `player`

答案 3 :(得分:1)

SELECT COUNT(*) 
FROM (
    SELECT Id 
    FROM accounts.account 
    UNION ALL 
    SELECT player 
    FROM players.player ) AS BothTables

答案 4 :(得分:0)

 int notify_token;
 notify_register_dispatch("com.apple.springboard.lockstate", &notify_token,dispatch_get_main_queue(), ^(int token) {
 uint64_t state = UINT64_MAX;
 notify_get_state(token, &state); 
 if(state == 0) {
 NSLog(@"unlock device");
 } else {
 NSLog(@"lock device");
 }