I'm trying to count all the records from multiple tables that have attr3
as a value of 1.
This is what I have so far:
SELECT 'Dept' AS table_name, COUNT(*)
FROM table1, table2
WHERE table1.attr3='1' AND table2.attr3='1'
The problem I am having is that it's showing the wrong number. It should display as 7
, but instead it's 12
.
I have to write it in such a way because attr3
is a foreign key so some solutions may come up with attr3 is ambiguous
Anyone know where I may be going wrong? Thank you
EDIT
I then want to apply the same query two more times but with different values to get separate counts:
SELECT 'Dept' AS table_name, COUNT(*)
FROM table1, table2
WHERE table1.attr3='2' AND table2.attr3='2'
Minimizing code would be a big plus!
You should use UNION
, not JOIN
, to combine the two tables, since you're not relating rows to each other between the tables. Then use GROUP BY
to get the counts for each attr3
.
SELECT attr3, COUNT(*)
FROM (
SELECT attr3 FROM table1
UNION ALL
SELECT attr3 FROM table2
) AS u
GROUP BY attr3
It might be better to do the counts in each table separately, then sum them. If you have an index on attr3
, this will be able to take advantage of it.
SELECT attr3, SUM(count)
FROM (
SELECT attr3, COUNT(*) AS count
FROM table1
GROUP BY attr3
UNION ALL
SELECT attr3, COUNT(*)
FROM table2
GROUP BY attr3
) AS u
GROUP BY attr3
Make sure you use UNION ALL
, not just UNION
, since by default it will remove duplicates.
The comma operator creates a Cartesian product. That produces way more rows than you want (under most circumstances). Instead, use union all
along with your condition:
SELECT 'Dept' AS table_name, COUNT(*)
FROM ((select attr3 from table1) union all
(select attr3 from table2)
) t
WHERE attr3 = '1';
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.