0

Is there a way i can select the COUNT with two table with one single query.

At the moment i have the following and it doesn't work correctly.

SELECT 
COUNT(t1.id) as t1_amount,
COUNT(t2.id) as t2_amount
FROM
table1 t1,
table2 t2

2 Answers 2

7

Here is one way:

select (select count(*) from table1) as t1_amount,
       (select count(*) from table2) as t2_amount

Here is another way:

select t1.t1_amount, t2.t2_amount
from (select count(*) as t1_amount from table1) t1 cross join
     (select count(*) as t2_amount from table2) t2

Your method does not work because the , in the from clause does a cross join. This does a cartesian product between the two tables.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Gordon which method is more efficient?
@bluebill1049 . . . They should be the same in terms of efficiency. Personally, I prefer the second approach because I tend to avoid select in select statements.
Thanks Gordon, i will follow your advice
2

As they are two separate queries and you want them in the same result set, use a UNION:

(SELECT COUNT(*) AS `table1_total` FROM `table1`)
  UNION
(SELECT COUNT(*) AS `table2_total` FROM `table2`);

1 Comment

Thanks Joshua for the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.