SQL基础
创建删除DB
创建:
1
CREATE DATABASE dbName;
删除:
1
DROP DATABASE dbName;
创建删除表
创建:
1
CREATE TABLE xxx (colum1 dataType,colum2 dataType);
删除:
1
DROP TABLE tableName;
修改表结构:
1
2ALTER TABLE XXX ADD COLUMN columName type;
ALTER TABLE XXX DROP COLUMN columnName;
增删改查
查询
1
SELECT * | xx,xx FROM xxxTable WHERE XXX AND XXX;
增加
1
INSERT INTO xxName (column,column) VALUES (xx,xx);
更新
1
UPDATE xxName SET colum=xxx, colum=xxx WHERE XXX;
删除
1
DELETE FROM xxName WHERE XXX;
主键和外键
非空和唯一性
1
2
3CREATE TABLE xxName(id int, name varchar(50) NOT NULL UNIQUE);
CREATE TABLE xxname(id int, name varchar(50) NOT NULL,CONSTRAINT unique_name UNIQUE(name));
CONSTRAINT unique_name UNIQUE (name, category);主键
1
id int PRIMARY KEY,
外键
1
2movie_id int REFERENCES movies(id), | movie_id int REFERENCES movies,
FOREIGN KEY (movie_id) REFERENCES movies
聚合函数
count(column_name):not null
sum(column_name)
avg(column_name)
max(column_name)
min(column_name)
数据库查询
比较运算符
1
等于(=),小于(<),大于(>),小于或等于(<=),大于或等于(>=),不等于(<>)
排序
1
SELECT * FROM xxx ORDER BY XX DESC(递减);默认递增(ASC)
分组
1
2GROUP BY columnName
HAVING COUNT(*) > 1 分组的搜索数量大于1CHECK & IN
1
2duration int CHECK (duration>0)
WHERE id in (2,3)Aliases
1
column and table - SELECT m.title as tit FROM Movies m
多表查询
Inner Joins
1
SELECT * FROM Movies INNER JOIN Reviews ON Movies.id=Reviews.movie_id
Outer Joins
1
2SELECT * FROM Movies LEFT OUTER JOIN Reviews ON Movies.id=Reviews.movie_id;会去除所有Movies(左)的数据
SELECT * FROM Movies RIGHT OUTER JOIN Reviews ON Movies.id=Reviews.movie_id;会去除所有Reviews(右)的数据Subqueries
1
2SELECT SUM(sales) FROM Movies WHERE id IN (SELECT movie_id from Promotions where category='Non-cash')
SELECT SUM(m.sales) FROM Movies m INNER JOIN Promotions p ON m.id=p.movie_id WHERE p.category='Non-cash'