我需要计算来自不同(!)表的行数并将结果保存为某种统计信息。该脚本非常简单并且按预期工作,但我想知道是否最好使用带有(在这种情况下)8个子查询的单个查询,或者我是否应该使用单独的8个查询,或者是否有更好、更快和更多的查询先进的解决方案...
我将 MySQLi 与准备好的语句一起使用,因此单个查询可能如下所示:
$sql = 'SELECT
(SELECT COUNT(cat1_id) FROM `cat1`),
(SELECT COUNT(cat2_id) FROM `cat2`),
(SELECT COUNT(cat2_id) FROM `cat2` WHERE `date` >= DATE(NOW())),
(SELECT COUNT(cat3_id) FROM `cat3`),
(SELECT COUNT(cat4_id) FROM `cat4`),
(SELECT COUNT(cat5_id) FROM `cat5`),
(SELECT COUNT(cat6_id) FROM `cat6`),
(SELECT COUNT(cat7_id) FROM `cat7`)';
$stmt = $db->prepare($sql);
$stmt->execute();
$stmt->bind_result($var1, $var2, $var3, $var4, $var5, $var6, $var7, $var8);
$stmt->fetch();
$stmt->free_result();
$stmt->close();
而单独的查询看起来像这样(x 8):
$sql = 'SELECT
COUNT(cat1_id)
FROM
`cat1`';
$stmt = $db->prepare($sql);
$stmt->execute();
$stmt->bind_result($var1);
$stmt->fetch();
$stmt->free_result();
$stmt->close();
所以,与这种查询相关的更快或“更好的风格”(例如统计信息,计数器..)