Home > Database > Mysql Tutorial > body text

How to use MySQL DISTINCT clause on multiple columns?

王林
Release: 2023-08-27 08:13:13
forward
1372 people have browsed it

如何在多个列上使用 MySQL DISTINCT 子句?

We can use DISTINCT clause on multiple columns in MySQL. In this case, the uniqueness of a row in the result set will depend on the combination of all columns.

Example

Consider the following table "testing" having 10 rows -

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)
Copy after login

Now, if we apply on two columns named Fname and Lname DISTINCT clause, then we will get unique rows based on the combination of these two columns. It can be observed from the following query -

mysql> Select DISTINCT FNAME,LNAME from testing2;
+---------+---------+
| 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)
Copy after login

MySQL returns 9 rows as the result set as they have unique combination of values ​​from "Fname" and "Lname" columns.

The above is the detailed content of How to use MySQL DISTINCT clause on multiple columns?. 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!