Home > Database > Mysql Tutorial > body text

Can we use MySQL GROUP BY clause for multiple columns just like MySQL DISTINCT clause?

王林
Release: 2023-08-24 17:33:02
forward
907 people have browsed it

我们可以像使用 MySQL DISTINCT 子句一样对多个列使用 MySQL GROUP BY 子句吗?

Yes, it is possible to use MySQL’s GROUP BY clause to group multiple columns, just like we can use MySQL’s DISTINCT clause. Consider the following example, in the first query we have used the DISTINCT clause and the second query using the GROUP BY clause on the 'fname' and 'Lname' columns of the table named 'testing'.

mysql> Select * from testing;
+------+---------+---------+
| id   | fname   | Lname   |
+------+---------+---------+
|  200 | Raman   | Kumar   |
|  201 | Sahil   | Bhalla  |
|  202 | Gaurav  | NULL    |
|  203 | Aarav   | NULL    |
|  204 | Harshit | Khurana |
|  205 | Rahul   | NULL    |
|  206 | Piyush  | Kohli   |
|  207 | Lovkesh | NULL    |
|  208 | Gaurav  | Kumar   |
|  209 | Raman   | Kumar   |
+------+---------+---------+
10 rows in set (0.00 sec)

mysql> Select DISTINCT FNAME,LNAME from testing;
+---------+---------+
| FNAME   | LNAME   |
+---------+---------+
| Raman   | Kumar   |
| Sahil   | Bhalla  |
| Gaurav  | NULL    |
| Aarav   | NULL    |
| Harshit | Khurana |
| Rahul   | NULL    |
| Piyush  | Kohli   |
| Lovkesh | NULL    |
| Gaurav  | Kumar   |
+---------+---------+
9 rows in set (0.00 sec)

mysql> Select Fname, LNAME from testing GROUP BY Fname,Lname;
+---------+---------+
| Fname   | LNAME   |
+---------+---------+
| Aarav   | NULL    |
| Gaurav  | NULL    |
| Gaurav  | Kumar   |
| Harshit | Khurana |
| Lovkesh | NULL    |
| Piyush  | Kohli   |
| Rahul   | NULL    |
| Raman   | Kumar   |
| Sahil   | Bhalla |
+---------+---------+
9 rows in set (0.00 sec)
Copy after login

The only difference is that the result set returned by the MySQL query using the GROUP BY clause is sorted, while the result set returned by the MySQL query using the DISTINCT clause is not sorted.

The above is the detailed content of Can we use MySQL GROUP BY clause for multiple columns just like MySQL DISTINCT clause?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!