I count values from multiple columns like this:
SELECT COUNT(column1),column1 FROM table GROUP BY column1 SELECT COUNT(column2),column2 FROM table GROUP BY column2 SELECT COUNT(column3),column3 FROM table GROUP BY column3
This returns for example for column1 array(attr1 => 2000, attr2 => 3000...) (Each column has specific and few values). The problem is that "table" in my application can be a query with some joins and where clauses, that may take 0.1sec. By doing all that counts "table" is computed each time again which is not necessary. Is there any way to take the results i want with one query, or "cache" the query that produces table? Otherwise i believe denormalization would be the only solution here. And i want the same results with the above queries. I am using mysql-myisam.
We can use GROUP BY to group together rows that have the same value in the Animal column, while using COUNT() to find out how many ID's we have in each group. It returns a table with three rows (one for each distinct animal).
The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.
We can group the resultset in SQL on multiple column values. When we define the grouping criteria on more than one column, all the records having the same value for the columns defined in the group by clause are collectively represented using a single record in the query output.
It's hard to know how to help you without understanding the context / structure of your data, but I believe this might help you:
SELECT SUM(CASE WHEN column1 IS NOT NULL THEN 1 ELSE 0 END) AS column1_count ,SUM(CASE WHEN column2 IS NOT NULL THEN 1 ELSE 0 END) AS column2_count ,SUM(CASE WHEN column3 IS NOT NULL THEN 1 ELSE 0 END) AS column3_count FROM table
One solution is to wrap it in a subquery
SELECT * FROM ( SELECT COUNT(column1),column1 FROM table GROUP BY column1 UNION ALL SELECT COUNT(column2),column2 FROM table GROUP BY column2 UNION ALL SELECT COUNT(column3),column3 FROM table GROUP BY column3 ) s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With