Home > Database > Mysql Tutorial > body text

关于MySQL与SQLLite的Group By排序原理的区别

WBOY
Release: 2016-06-07 16:43:24
Original
980 people have browsed it

当我们对一个表的记录进行group by的时候,在未明确使用sum、min、max等聚合函数的时候,group by 的排序规则,如下对比了MySQL和

当我们对一个表的记录进行group by的时候,,在未明确使用sum、min、max等聚合函数的时候,group by 的排序规则,如下对比了MySQL和SQLLite

大家都知道,group by的时候,数据库是遍历数据库表的所有记录进行匹配处理的。

下面的SQL目的是为了查询表中groupid相同的记录中,最新时间的一条消息,给出mysql和sqllite的语句区别:

MYSQL语句

SELECT * FROM(
SELECT t.id,t.data_id,t.send_username,t.recv_username,t.message,IFNULL(NULLIF(t.groupid,''),t.recv_username) AS groupid,t.`created_date`
FROM tb_push_data t WHERE STATUS = 0 ORDER BY t.`created_date` desc,t.id desc
) t1
GROUP BY t1.groupid
ORDER BY t1.`created_date` DESC,t1.id DESC

SQLLite语句

select * from(
select t.id,t.data_id,t.login_username,t.send_username,t.recv_username,t.message,ifnull(nullif(t.groupid,''),t.send_username) as groupid,t.time
from tb_recved_data t where status = 0 order by t.time asc, t.id asc
) t1
group by t1.groupid
order by t1.time desc,t1.id desc

大家注意对比SQL可以发现,子查询最后的ORDER BY 中,在MYSQL中使用 ASC,而在SQLLite中我们使用 DESC
 
原因就是:MYSQL在遍历表记录的时候当发现重复的group字段时,是忽略的。而SQLLite是覆盖的。
 
所以我们为了获取最晚发送的一条记录时,在mysql中使用desc,sqllite中使用asc

--------------------------------------分割线 --------------------------------------

Ubuntu 14.04下安装MySQL

《MySQL权威指南(原书第2版)》清晰中文扫描版 PDF

Ubuntu 14.04 LTS 安装 LNMP Nginx\PHP5 (PHP-FPM)\MySQL

Ubuntu 14.04下搭建MySQL主从服务器

Ubuntu 12.04 LTS 构建高可用分布式 MySQL 集群

Ubuntu 12.04下源代码安装MySQL5.6以及Python-MySQLdb

MySQL-5.5.38通用二进制安装

--------------------------------------分割线 --------------------------------------

本文永久更新链接地址:

linux

Related labels:
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!