I need a query to find the count based on the multiple table. Please Check the below details
I am having 3 tables as table_1, table_2, table_3 and table_1 is the primary table, and other 2 are inherited from the primary. these table has the common value of profile_id column. Check this sample query counter
SELECT COUNT(profile_id)
from table_1
WHERE profile_id IN (SELECT profile_id FROM table_2)
the above query returns the count based on the table_2 profile id
. But i need query with all the tables separately like as below
SELECT COUNT(profile_id) as table_2count,
COUNT(profile_id) as table_3count
FROM table_1 WHERE (the two condition)
In above query table_2count is based on the table_2 profiles and table_3count will be based on the table_3. How can i merge these values into single query. Please suggest some methods to find out the count values.
You can use 2 subqueries to achieve that:
SELECT
t1.*, -- get all data from t1 + two counts from t2 and t3
(SELECT COUNT(t2.profile_id)
FROM table_2 t2
WHERE t2.profile_id = t1.profile_id) as count2,
(SELECT COUNT(t3.profile_id)
FROM table_3 t3
WHERE t3.profile_id = t1.profile_id) as count3
FROM table_1 t1
WHERE <your conditions for table_1 go here>
If profile_id
is unique in table_1
and you have foreign keys in table_2
and table_3
, you don't really need to join back with table_1, what you need is something like this.
SELECT
(SELECT COUNT(distinct profile_id) FROM table_2) table_2count,
(SELECT COUNT(distinct profile_id) FROM table_3) table_3count
If you really need a join or there are no FKs defined, you can use this
SELECT
COUNT(distinct t2.profile_id) table_2count,
COUNT(distinct t3.profile_id) table_3count
FROM table_1 t1
LEFT JOIN table_2 t2 on t1.profile_id = t2.profile_id
LEFT JOIN table_3 t3 on t1.profile_id = t3.profile_id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.