記事のディレクトリ
実験要件
目的:データベースにおけるインデックスの役割を理解し、インデックスの適用を理解する
- Python SQLステートメントテスト
2つの同一の学生テーブルを作成してください。
学生テーブル1には、プライマリキーID(自動インクリメント、学生ID)、学生名nane、学生スコア、
学生テーブル2には、プライマリキーID(自動インクリメント、学生ID)が含まれます。 )、学生名なね、学生スコア
、学生表2のスコアにインデックスを追加してください
リレーショナルデータにインデックスを追加する場合と追加しない場合の違い:
フィールドのインデックスを作成すると、フィールドに関するツリー構造が生成されます。
つまり、where条件を使用する場合:例:where score> 90
- インデックスなし:順番に検索------> O(n)
- インデックスの追加:double search ------> O(log2n)
- テストを実行するPythonのORMメソッドORMメソッドを
使用して、同じデータを2つの学生テーブルに挿入してください-100,000、名前は漢字のランダムな組み合わせを使用して生成され、スコアは0-100の均等に分散されてランダムに生成されます。
スコアが95を超える2つのテーブルで同時にクエリを実行する学生の場合、スコアにインデックスを作成することで検索時間の効率が向上するかどうかをテストします。
1つは、SQLが学生テーブルを作成することです。
1.1作成テーブル
コード表示:
#Python 数据库
import pymysql
db = pymysql.connect(user='test',host='localhost', password='123456',database='testdb',charset='utf8')
cursor = db.cursor() #创建游标 游标的每个动作会执行到数据库里面
sql = """create table student1(
id int auto_increment primary key,
name varchar(20) not null,
score int) """
cursor.execute(sql)
sql = """create table student2(
id int auto_increment primary key,
name varchar(20) not null,
score int) """
cursor.execute(sql)
#添加索引
sql = "create index score_index on student2(score)"
#删除索引
#sql = "creat index score_index on student2()"
cursor.execute(sql)
cursor.close()
db.close()
結果表示:
1.2インデックスを表示
学生からインデックスを表示1 //インデックスなし
SHOW INDEX FROM student2 //インデックスを追加
2、データを作成するORMの方法
2.1ビルドデータ
キーコードは次のとおりです(例)。
#创建类
class Student1(Base):
__tablename__ ='student1'#表名-->数据库中表student1
id = Column(Integer, primary_key=True)
name = Column(String)
score = Column(Integer,default=60)#默认60
class Student2(Base):
__tablename__ ='student2'#表名-->数据库中表student2
id = Column(Integer, primary_key=True)
name = Column(String)
.....
.....
.....
for i in range(100):
#随机生成 两个字的姓名 分数
name = ''.join(random.sample('张王天男别奥法妹大那几年安东尼的技能但是否能单反',2))
score = random.randint(0,100)
session.add(Student1(name=name, score=score))
session.add(Student2(name=name, score=score))
#每调用一次,塞入数据库执行一次
session.commit()
'''
由于插入数据需要消耗时间 当插入大量数据可作如下改动
if i%10 == 0
session.commit()
'''
print(i)
2.2クエリデータ
コードは次のとおりです(例):
#SqlAlchemy查询建立也需要时间
students = session.query(Student1).filter(Student1.score<50).all()
students = session.query(Student1).filter(Student2.score<50).all()
#SqlAlchemy真实测试的查询
#100条数据,不见索引查询的快
#1000条数据,建立索引查询的快
print(time.clock())
students = session.query(Student1).filter(Student1.score>90).all()
print(time.clock())
students = session.query(Student2).filter(Student2.score>90).all()
print(time.clock())
- 概要:インデックスクエリは大量のデータに適しています