用简单通俗的话来记录自己对架构的理解
1.条件复合语句
1.limit、offset
limit 语法有两种写法s
-
一个参数 : limit x
其中x是一个整数,表示返回x条目记录。
2.两个参数: limit x , y
其中x , y 都是整数,表示跳过x 条记录,返回 y 条记录,即 LIMIT <skip>, <count>
此外limit 还与offset关键词结合,语法是: limit x offset y
表示跳过 y 条记录,返回 x 条记录 ,即 LIMIT <count> OFFSET <skip>
乍一看 limit x , y 和limit x offset y 的语义很接近,千万不要搞混了。
2.实际应用
1.限制总数的删除数据的场景
数据表:
| url | pkg | time |
|---|---|---|
| http://www.baidu.com | com.baidu | 65865263800 |
要求:表内数据保持50条,添加新数据时,删除最老数据
思路:条件判断>49并且删除大于限制数目。
简洁版:
delete from search_history where (select count(keyword) from search_history
)> 2 and keyword in (select keyword from search_history order by time desc limit (select count(keyword) from search_history) offset 2 )
逻辑版:
List<SearchHistory> searchHistoryList = searchHistoryDao.queryAll();
int size = searchHistoryList.size();
while(size > 49){
searchHistoryDao.deleteUrl(searchHistoryList.get(size -1).url);
searchHistoryList = searchHistoryDao.queryAll();
size = serachHistoryList.size();
}
代码整洁度:一行SQLite语句解决
效率:耗时4.6ms,远低于8.6ms
| 实现方式 | 代码整洁度 | 耗时(ms) |
|---|---|---|
| 复合sqlite | 一行 | 4.6 |
| 简单sqlite | 多行 | 8.6 |
SQL LIMIT与OFFSET用法及优化
2909

被折叠的 条评论
为什么被折叠?



