Home Database Mysql Tutorial mysql中distinct去除重复值方法

mysql中distinct去除重复值方法

Jun 07, 2016 pm 05:52 PM
distinct

在使用mysql时,有时需要查询出某个字段不重复的记录,虽然mysql提供 有distinct这个关键字来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是用它来返回不重记录的所有值。其原因是 distinct只能返回它的目标字段

,而无法返回其它字段,这个问题让我困扰了很久,用distinct不能解决的话,我只有用二重循环查询来解决,而 这样对于一个数据量非常大的站来说,无疑是会直接影响到效率的。所以我花了很多时间来研究这个问题

mysql的DISTINCT的关键字有很多你想不到的用处
1.在count 不重复的记录的时候能用到
比如SELECT COUNT( DISTINCT id ) FROM tablename;
就是计算talbebname表中id不同的记录有多少条

2,在需要返回记录不同的id的具体值的时候可以用
比如SELECT DISTINCT id FROM tablename;
返回talbebname表中不同的id的具体的值

3.上面的情况2对于需要返回mysql表中2列以上的结果时会有歧义
比如SELECT DISTINCT id, type FROM tablename;
实际上返回的是 id与type同时不相同的结果,也就是DISTINCT同时作用了两个字段,必须得id与tyoe都相同的才被排除了,与我们期望的结果不一样


 代码如下 复制代码

CREATE TABLE `student` (                  
           `name` varchar(20) NOT NULL DEFAULT '', 
           `age` int(10) DEFAULT '0'               
         ) ENGINE=InnoDB DEFAULT CHARSET=latin1

1.测试一
select * from student;        
a    5
a    5
c    0

用distinct过滤掉两列都相同的记录

 代码如下 复制代码
select distinct name,age from student;

返回
a    5
c    0

2.测试二
将表student的数据改为如下:

 代码如下 复制代码

select * from student;
c    2
c    5

select distinct name,age from student;

返回如下,说明distinct后面有多于一列的字段时,只有每列的值完全相同才过滤
c    2
c    5

3.测试三

 代码如下 复制代码
select * from student;
name age height

c    2    123
c    2    456
b    20    222

 代码如下 复制代码

group by按两列同时分组
select name,age,sum(height) from student group by name,age;
b    20    222
c    2    579

group by按两列同时分组,同时在后面加上having的条件

 代码如下 复制代码
select name,age,sum(height) as n from student group by name,age having n > 500;

返回
c    2    579

4.测试四
关于group by后面limit的测试

 代码如下 复制代码
select songname,sengerid,count(sengerid) as n from t_song group by songname,sengerid having n > 1 ORDER BY n DESC,songid ASC limit 10;

未知    8738    40
共同渡过    1432    24
风继续吹    1432    23
倩女幽魂    1432    23
无心睡眠    1432    23
罗百吉超嗨派对连续组曲    780    19
拒绝再玩    1432    19
风再起时    1432    18
每天爱你多一些    1480    18
千言万语    1794    18

 代码如下 复制代码
select songname,sengerid,count(sengerid) as n from t_song group by songname,sengerid having n > 1 ORDER BY n DESC,songid ASC limit 5;

未知    8738    40
共同渡过    1432    24
风继续吹    1432    23
倩女幽魂    1432    23
无心睡眠    1432    23

经过以上两个测试可以看出,如果sql语句中含有limit,limit是对用group by进行分组,并进行相关计算以后的limit操作,而不是对limit后面的指定记录数进行分组,从n那一列的数据每一行的值都大于10就可以看出来。

5.测试五
用以下的两种形式的distinct均可以得到相同的记录数,写法不一样,结果是一样的。

 代码如下 复制代码

select count(distinct(songid)) from feedback;

select count(distinct songid) from feedback;

6.测试六
field singername is string,max(singername),如果singername有些列为空,有些列不为空,则max(singername)取非空的值,如果一列为zxx,一列为lady,则取zxx,按字母顺利取的。

 代码如下 复制代码
select feedback_id,songid,songname,max(singername),max(time) as new_time from feedback group by songid order by new_time desc;

7.Sql语句中where,group by,order by及limit的顺序
where xxx,group by xxx,order by xxx,limit xxx

8.关于group by与count的问题
如果sql语句中含有group by,则最好不要将count sql转换为select count(*) from xxx,否则select与from之间的字段很有可能是后面要使用的,例如

 代码如下 复制代码

select feedback_id,songid,songname,max(singername),max(time) as new_time from feedback group by songid order by new_time desc;

MySQL Query Error: SELECT COUNT(*) FROM feedback GROUP BY songid ORDER BY new_time DESC Error Info:Unknown column 'new_time' in 'order clause'

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Explain the role of InnoDB redo logs and undo logs. Explain the role of InnoDB redo logs and undo logs. Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL for Beginners: Getting Started with Database Management MySQL for Beginners: Getting Started with Database Management Apr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

MySQL vs. Other Databases: Comparing the Options MySQL vs. Other Databases: Comparing the Options Apr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

Explain the InnoDB Buffer Pool and its importance for performance. Explain the InnoDB Buffer Pool and its importance for performance. Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL: Structured Data and Relational Databases MySQL: Structured Data and Relational Databases Apr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

Learning MySQL: A Step-by-Step Guide for New Users Learning MySQL: A Step-by-Step Guide for New Users Apr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

See all articles