sql基础知识
select查询语法
查询账单数量最高的三个国家
select BillingCity,count(Genre.Name ),Genre.Name from Invoice,InvoiceLine,Track,Genre where Invoice.InvoiceId=InvoiceLine.InvoiceId and InvoiceLine.TrackId=Track.TrackId and Track.GenreId=Genre.GenreId group by BillingCity order by count(Genre.Name ) desc limit 3;
规范化表的规则:
1.每行的列数相同。
2.存在唯一的键,行中所有内容均与键相关。
3.与键无关的数据属于其他表。
4.表中不应隐含不存在的关系
表内外连接
select products.name, products.sku, count(*) as num from products join sales on products.sku = sales.sku group by products.sku;
SQL 支持多种连接类型。上面的连接称为 inner join(内连接),这是最常用的连接类型。在 SQL 中,连接默认指的就是内连接,不需特别说明。
其次常用的是 left join(左连接)及其镜像伙伴 right join(右连接)。“左”和“右”分别指连接运算符左侧和右侧的表。(在上例中,左侧的表是 products,右侧的表是 sales。)
(就像“join”实际是“inner join”的简称一样,“left join”实际是“left outer join”的简称。但在 SQL 中直接输入“left join”即可,这样可减少键盘操作。我们不妨就这样做。)
创建数据库表结构
create table tb_name( column1 type A primary key, column2 type B references AA(db0_name), );
删除
删除库:drop database db_name
删除表:drop table tb_name
主键
主键:表中经常有一个列或多列的组合,其值能唯一地标识表中的每一行。
单个主键时可以在创建列时声明
多个主键时可以在末尾统一声明
外键
不同引用自他表的外键可组合成主键。
外键:外键表示了两个关系之间的相关联系。
自连接
自连接:连接的表都是同一个表,同样可以由内连接,外连接各种组合 方式,按实际应用去组合。
此查询旨在找到配对的室友
select a.id, b.id, a.building, a.room from residences as a, residences as b where a.building = b.building and a.room = b.room and a.id<b.id order by a.building, a.room;
DB-API
查询sql
import sqlite3 db = sqlite3.connect("students")= c = db.cursor() query = "select name, id from students order by name;" c.execute(query) rows = c.fetchall() print rows db.close()
插入、删除SQL,必须commit
import sqlite3 db = sqlite3.connect("testdb") c = db.cursor() c.execute("insert into balloons values ('blue', 'water') ") db.commit() db.close()
子查询
子查询就是指的在一个完整的查询语句之中,嵌套若干个不同功能的小查询,从而一起完成复杂查询的一种编写形式
select avg(bigscore) from (select max(score) as bigscore from mooseball group by team)as maxes;
创建视图
视图:视图是从一个或多个表(或视图)导出的表。视图与表不同,视图是一个虚表,即视图所对应的数据不进行实际存储。
create view view_name as select...
是否能在视图上更新表,取决于特定数据库
在数据库中使用 CSV
在 SQLite 中使用 CSV 非常简单 :)
SQLite 支持导入和导出 CSV 文件。
将数据库中的数据导出为 CSV 文件
sqlite> .mode csv
sqlite> .output newFile.csv
sqlite> SELECT * FROM myTable;
sqlite> .exit
将 CSV 文件导入表中
$ sqlite3 new.db <--- 如果要将 csv 文件导入新数据库中,切记要先创建该数据库。
sqlite> CREATE TABLE myTable() <--- 构建您的模式!
sqlite> .mode csv
sqlite> .import newFile.csv myTable