سؤال

I need to get the row count from multiple tables using the same conditions with pdo. For example, this would give me the row count for table 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();

Now, I want to run the same query, but with different tables... for instance... users1, users2, users3, users4, etc.

The tables are all different of course, but all will have columns account_id and computer_name. Is it possible to join all these tables in some way and still get a count for each specifically or will I need to run multiple selects to the database for each one?

The goal is to create a display for the logged in user which shows how many records are in the database for different tables.

Expected result is something where I can get total row counts for each table that meet the WHERE clause conditions :

users1 = 50
users2 = 34
users3 = 82
...etc
هل كانت مفيدة؟

المحلول

You could do this query:

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')

And then pass the appropriate number of parameters:

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

نصائح أخرى

Yes, in order to get the count you will have to join all the data tables together on the appropriate foreign keys.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top