0

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

好的,有几张桌子;

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);
4

3 回答 3

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";
于 2013-02-02T19:43:51.977 回答
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
于 2013-02-02T19:08:14.547 回答
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 ) );

在这里演示 SQLFIDDLE

于 2013-02-02T19:44:28.630 回答