[Notes] DISTINCT keyword in MySQL

In MySQL, the DISTINCT keyword is used to return unique records in the query result set. It can be applied to a single column, multiple columns, or the entire query result set. Here are some common uses of the DISTINCT keyword:

  1. Query the unique values ​​of a single column:

    SELECT DISTINCT column_name FROM table_name;
    

    This statement will return unique values ​​for a column in the specified table.

  2. Query unique combinations of multiple columns:

    SELECT DISTINCT column1, column2 FROM table_name;
    

    This statement will return unique combinations of multiple columns in the specified table. Only if the combined value of these columns is unique in the result set, it will be returned.

  3. Query the unique records of the entire result set:

    SELECT DISTINCT * FROM table_name;
    

    This statement will return unique records for all columns in the specified table.

It should be noted that using the DISTINCT keyword will sort and deduplicate the query results, which may have a certain impact on performance. If you can expect large result set sizes, you can consider other optimizations to improve query performance, such as using indexes or appropriate filters.

In addition, the DISTINCT keyword can also be used in conjunction with aggregate functions (such as COUNT, SUM, etc.) to obtain unique values ​​for a specific column or the entire result set and perform aggregate calculations.

おすすめ

転載: blog.csdn.net/weixin_44624036/article/details/134417212