暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

sqlite查找结果的排序与限制

与C同行 2021-07-14
2647
使用select
语句查寻结果有时候需要将结果按照一定的规则排序,这个时候可以使用SQL查询语句的order by
将结果进行排序。有些时候需要得到查询结果的一部分而不是全部,这个时候可以使用limit
限制结果的个数。由于前面没有讲外键约束,在这里补充一下,外键约束一般是定义关系的,比如一对一,一对多,多对多等关系。
看一下如何使用order by
来排序和使用limit
来限制查询结果:
""" limit和order by

稍微成熟点的select语句
SELECT ... FROM table_name [WHERE condition]
[ORDER BY column_1, column_2, ...] [LIMIT count [OFFSET count]]

limit:限制查询结果的行数
order by:按照指定列排序查询结果

外键限制
foreign key (this_column_names) references table_name (reference_column_names)

the statistics of this file:
lines(count) understand_level(h/m/l) classes(count) functions(count) fields(count)
000000000078 ----------------------l 00000000000000 0000000000000001 ~~~~~~~~~~~~~
"""


import time
import sqlite3

__author__ = '与C同行'


def print_pretty_outcome(cursor):
print('-' * 80)
all_outcome = cursor.fetchall()
for column_desc in cursor.description:
print(f'{column_desc[0]:<20}', end='')
print()
for item in all_outcome:
for cell in item:
try:
print(f'{cell:<20}', end='')
except TypeError:
cell = 'None'
print(f'{cell:<20}', end='')
print()
print('-' * 80)
print()


if __name__ == '__main__':
print(f'当前时间:{time.ctime()}')
conn = sqlite3.connect('learn.db')
c = conn.cursor()

c.execute('''create table salary_tb(
name text not null,
salary integer,
person_id integer,
foreign key(person_id) references report_tb(student_number) )'''
)
c.executemany('insert into salary_tb values (?, ?, ?)',
(('杨过', 10000, 1901),
('啊龙', 8000, 1902),
('雄儿', 8000, 1903),
('业儿', 6000, 1904),
('业儿', 5000, 1904),
))
conn.commit()

print('使用limit语句限制查询数据行数')
c.execute('select * from salary_tb limit 2')
print_pretty_outcome(c)

print('limit和offset一起使用来偏移查询结果')
c.execute('select * from salary_tb limit 2 offset 1')
print_pretty_outcome(c)

print('使用order by语句来排序查询结果')
c.execute('select * from salary_tb order by salary limit 3')
print_pretty_outcome(c)

print('desc倒序排列')
c.execute('select * from salary_tb order by salary desc')
print_pretty_outcome(c)

c.close()
conn.close()

注意,源码中又新建了一个salary_tb表格,本部分内容使用这个表格来查询。
结果如下:

总结:limit
可以和offset
结合使用来偏移查询结果,order by
可以声明升序排序或者降序排序,完整的select
查询语句其实很长,想要完全掌握还需要逐渐熟悉。




文章转载自与C同行,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论