Home > Database > Mysql Tutorial > body text

mysql distinct的妙用

WBOY
Release: 2016-06-07 15:09:58
Original
1134 people have browsed it

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 顺便提下mysql的DISTINCT的关键字有很多你想不到的用处 1.在count 不重复的记录的时候能用到 比如SELECT COUNT( DISTINCT id ) FROM tablename; 就是计算talbebname表中id不同的记录有多少条 2,在需

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入

  顺便提下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都相同的才被排除了,与我们期望的结果不一样

  4.这时候可以考虑使用group_concat函数来进行排除,不过这个mysql函数是在mysql4.1以上才支持的

  5.其实还有另外一种解决方式,就是使用

  SELECT id, type, count(DISTINCT id) FROM tablename

  虽然这样的返回结果多了一列无用的count数据(或许你就需要这个我说的无用数据)

  返回的结果是 只有id不同的所有结果和上面的4类型可以互补使用,就是看你需要什么样的数据了

mysql distinct的妙用

source:php.cn
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!