MySQL filters duplicate data

Method 1: Add keyword DISTINCT

In mysql, you can use the "SELECT" statement and the "DISTINCT" keyword to perform deduplication queries and filter out duplicate data. The syntax is "SELECT DISTINCT field name FROM data table name;".

The syntax format of the DISTINCT keyword is: 

SELECT DISTINCT <字段名> FROM <表名>;

Among them, "field name" is the name of the field that needs to eliminate duplicate records. If there are multiple fields, separate them with commas.

Example

-- 示例1
SELECT DISTINCT name FROM Product WHERE price>100;

-- 示例2
SELECT DISTINCT name,age FROM student;

There are a few things to note when using the DISTINCT keyword:

  • The DISTINCT keyword can only be used in SELECT statements.

  • When deduplicating one or more fields, the DISTINCT keyword must be at the front of all fields.

  • If there are multiple fields after the DISTINCT keyword, the multiple fields will be combined to deduplicate. That is to say, only when the combination of multiple fields is exactly the same, they will be deduplicated.

SELECT When using statements to perform simple data queries in MySQL  , all matching records are returned. If some fields in a table do not have unique constraints, duplicate values ​​may exist in these fields. In order to query unique data, MySQL provides  DISTINCT keywords.

The main function of the DISTINCT keyword is to filter duplicate data in one or more fields in the data table and return only one piece of data to the user.


Method 2: Group by GROUP By

One principle of group by is that among all the columns after select, the columns that do not use aggregate functions must appear after group by.

Example

-- GROUP By后面出现的属性并需在SELECT后面也出现
SELECT name FROM Product WHERE price<100 GROUP By name;

Guess you like

Origin blog.csdn.net/qq_40861800/article/details/125485422