Home  >  Article  >  Database  >  关于MySQL与SQLLite的GroupBy排序原理的区别_MySQL

关于MySQL与SQLLite的GroupBy排序原理的区别_MySQL

WBOY
WBOYOriginal
2016-06-01 13:02:07849browse

当我们对一个表的记录进行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

Statement:
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