If we want to use grouping function on non-grouped fields in SELECT query, we must use GROUP BY clause. The general syntax can be as follows
SELECT group_function1,…, non-group-column1,… from table_name GROUP BY column_name;
mysql> Select COUNT(*), id from Student GROUP BY id; +----------+------+ | COUNT(*) | id | +----------+------+ | 1 | 1 | | 1 | 2 | | 1 | 15 | | 1 | 17 | | 1 | 20 | +----------+------+ 5 rows in set (0.00 sec) mysql> Select COUNT(*), address from Student GROUP BY id; +----------+---------+ | COUNT(*) | address | +----------+---------+ | 1 | Delhi | | 1 | Mumbai | | 1 | Delhi | | 1 | Shimla | | 1 | Jaipur | +----------+---------+ 5 rows in set (0.00 sec)
The fields after the GROUP BY clause can be different from the non-group fields given in the SELECT query.
The above is the detailed content of How can we use group function with non-group fields in MySQL SELECT query?. For more information, please follow other related articles on the PHP Chinese website!