gpt4 book ai didi

php - pdo - 作为单独的查询获取多个表的行数?

转载 作者:行者123 更新时间:2023-11-29 13:00:05 25 4
gpt4 key购买 nike

我需要使用 pdo 的相同条件从多个表中获取行数。例如,这将为我提供表users的行数。

$stmt = $db->prepare("SELECT * FROM `users` WHERE `account_id` = ? AND (`computer_name` = 'name1' OR `computer_name` = 'name2' OR `computer_name` = 'name3');
$stmt->execute(array($_SESSION['user']['account_id']));

$result = $stmt->fetchColumn();

现在,我想运行相同的查询,但使用不同的表...例如...users1users2user3users4

当然,这些表都不同,但都包含列 account_idcomputer_name。是否可以以某种方式连接所有这些表,并且仍然获得每个表的具体计数,或者我需要为每个表对数据库运行多个选择?

目标是为登录用户创建一个显示,显示数据库中不同表的记录数。

预期结果是我可以获得满足 WHERE 子句条件的每个表的总行数:

users1 = 50
users2 = 34
users3 = 82
...etc

最佳答案

您可以执行以下查询:

SELECT 'users' as tbl, count(*) as cnt FROM `users` 
WHERE `account_id` = ? AND (`computer_name` = 'name1' OR `computer_name` = 'name2' OR `computer_name` = 'name3')
UNION
SELECT 'users2' as tbl, count(*) as cnt FROM `users2`
WHERE `account_id` = ? AND (`computer_name` = 'name1' OR `computer_name` = 'name2' OR `computer_name` = 'name3')
UNION
SELECT 'users3' as tbl, count(*) as cnt FROM `users3`
WHERE `account_id` = ? AND (`computer_name` = 'name1' OR `computer_name` = 'name2' OR `computer_name` = 'name3')

然后传递适当数量的参数:

$stmt->execute(array_fill(0, 3, $_SESSION['user']['account_id']));

关于php - pdo - 作为单独的查询获取多个表的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23478408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com