计算多个表中的行数

时间:2013-02-02 19:02:34

标签: php mysql

我正在尝试做一些非常基本的事情,但不能完全理解这一点。我使用PHP和MySQLi(OOP)而不是MySQL。我可以使用多个单选select语句,然后将每个数字的计数放入变量中,但我认为它效率低。

好的,有几张桌子;

TABLE NAME: UCC_STAFF
id
email
username
password
status

TABLE NAME: UCC_TEMP_STAFF
id
email
username
password
status

TABLE NAME: UCC_TEMP_STUDENTS
id
email
username
password
status

TABLE NAME: UCC_VISITORS
id
email
username
password
status

我要做的是计算每个表中的行数,每行代表一个用户。正如我所解释的那样;使用一个表很容易,但是我想将结果与单个请求组合成一个数组,而不是将多个语句组合成多个变量。

所需结果的一个例子是:

$a = results('UCC_STAFF' => '35',
            'UCC_TEMP_STAFF' => '12',
            'UCC_STUDENTS' => '543',
            'UCC_VISITORS'  => '6',);

我想象的会是这样的;

$db_host = "dbhost";
$db_username = "username"; 
$db_pass = "password";
$db_name = "dbname";

$mysqli = new mysqli("$db_host", "$db_username", "$db_pass", "$db_name");

if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query  = "SELECT * FROM UCC_STAFF;";
$query .= "SELECT * FROM UCC_TEMP_STAFF;";
$query .= "SELECT * FROM UCC_STUDENTS;";
$query .= "SELECT * FROM UCC_VISITORS";

if ($mysqli->multi_query($query)) {

// Results into $results
// How do I do this, what goes here?    

    }

// Print Array
print_r ($results);

3 个答案:

答案 0 :(得分:2)

您可以通过一个查询来计算来自多个表的数据。

$query  = "SELECT ";
$query .= "(SELECT COUNT(*) FROM UCC_STAFF) AS count_staff, ";
$query .= "(SELECT COUNT(*) FROM UCC_TEMP_STAFF) AS count_temp_staff, ";
$query .= "(SELECT COUNT(*) FROM UCC_TEMP_STUDENTS) AS count_students, ";
$query .= "(SELECT COUNT(*) FROM UCC_VISITORS) AS count_visitors";

答案 1 :(得分:1)

创建一个

TABLE NAME: UCC_PEOPLE
id
email
username
password
status
type <-- use this field to distinguish different types

运行一个查询以获取记录的计数,而非记录本身

SELECT type, count(*) cnt, FROM UCC_PEOPLE GROUP BY type

答案 2 :(得分:0)

我认为你用UNION

寻找类似的东西
 $query  =(  (SELECT CONCAT('UCC_STAFF', '')as UCC_STAFF ,count(*)as count from UCC_STAFF )

              UNION ALL
              (SELECT CONCAT('UCC_TEMP_STAFF', '')as UCC_TEMP_STAFF ,count(*) from UCC_TEMP_STAFF )

              UNION ALL
              (SELECT CONCAT('UCC_TEMP_STUDENTS', '')as UCC_TEMP_STUDENTS ,count(*) from  UCC_TEMP_STUDENTS )

              UNION ALL
              (SELECT CONCAT('UCC_VISITORS', '')as UCC_VISITORS ,count(*) from UCC_VISITORS ) );

DEMO SQLFIDDLE HERE