zoukankan      html  css  js  c++  java
  • Sqlite 数据库插入标示字段 获取新Id 及利用索引优化查询

    sqlite的语法和sql server的语法是有一些区别的,比如插入数据,对于标示种子的字段,必须指定为NULL,而获得新id,在sql server中是
    SELECT @@IDENTITY [id]但是在sqlite中不是这样,而是
    insert into t_1(id,name)values(NULL,'赵玉开5');
    select last_insert_rowid() newid;注意获得新id的函数是last_insert_rowid()而不是last_insert_id(),last_insert_id()函数是mysql中获得新插入自增数字主键的函数。另外sqlite比较怪异的一点是,对于自增数字主键,必须指定为NULL值。
    最后推荐一下sqlite的开发工具 http://sqliteadmin.orbmu2k.de/
    请尊重作者的劳动,转载请保留链接 玉开的技术博客

    文章来自学IT网:http://www.xueit.com/html/2008-12/134_5125_00.html

    ===========================利用索引优化查询===========================

    在进行多个表联合查询的时候,使用索引可以显著的提高速度,刚才用SQLite做了一下测试。

    建立三个表:
    create table t1
    (id integer primary key,
    num integer not null,
    word1 text not null,
    word2 text not null);
    create table t2
    (id integer primary key,
    num integer not null,
    word1 text not null,
    word2 text not null);
    create table t3
    (id integer primary key,
    num integer not null,
    word1 text not null,
    word2 text not null);


    建立若干索引:
    t1表:在num,word1,word2上有复合索引
    t2表:在num,word1,word2上各有一个索引
    t3表:在word1上有一个索引
    create index idxT1 on t1(num,word1,word2);
    create index idxT2Num on t2(num);
    create index idxT2Word1 on t2(word1);
    create index idxT2Word2 on t2(word2);
    create index idxT3Word1 on t3(word1);


    向三个表中各插入10000行数据,其中num项为随机数字,word1和word2中是英文单词,三个表中对应的num,word1和word2列中都包含有部分相同值,但是它们在表中出现的顺序不同。

    速度测试结果:
    1) select count(*) from t1,t3 where t1.word2=t3.word2;
    很慢(t3.word2上没有索引)
    2) select count(*) from t3,t1 where t1.word2=t3.word2;
    很慢(t1.word2上没有独立索引)
    3) select count(*) from t1,t2 where t1.word2=t2.word2;
    很快(t2.word2上有索引)
    4) select count(*) from t2,t1 where t1.word2=t2.word2;
    很慢(t1.word2上没有独立索引)
    5) select count(*) from t1,t2 where t1.num=t2.num;
    很快(t2.num上有索引)
    6) select count(*) from t2,t1 where t1.num=t2.num;
    很快(t1的复合索引中,第一个列是num)
    7) select count(*) from t1,t3 where t1.num=t3.num;
    很慢(t3.num上没有索引)
    8) select count(*) from t3,t1 where t1.num=t3.num;
    很快(t1的复合索引中,第一个列是num)


    结论:在from子句后面的两个表中,如果第2个表中要查询的列里面带有索引,这个查询的速度就快,反之就慢。比如第三个查询,from后面的第2个表是 t2,t2在word2上有索引,所以这个查询就快,当输入SQL命令并回车后,查询结果就立即显示出来了,但是如果使用第4个查询命令(即把t1和t2 的位置互换),查询起来却用了1分零6秒。

    可见索引的建立对于提高数据库查询的速度是非常重要的。


    转载于



    返回导读目录,阅读更多随笔



    分割线,以下为博客签名:

    软件臭虫情未了
    • 编码一分钟
    • 测试十年功


    随笔如有错误或不恰当之处、为希望不误导他人,望大侠们给予批评指正。

  • 相关阅读:
    C++ Boost Thread 编程指南
    boost的Any库学习
    人生规划,关注未来,才能持续发展
    察言观色—看穿他人心理的6种方法
    MS SQL Server 2008发布与订阅
    WebService代理类中对枚举类型的序列化
    Winform注册和注销全局快捷键
    sql server中如何为数据表添加表的描述MS_Description
    如何修改SQL Server 2008数据库服务器名称
    IIS 上发布网站后编译器错误信息: CS0016: 解决办法
  • 原文地址:https://www.cnblogs.com/08shiyan/p/1832106.html
Copyright © 2011-2022 走看看