SQL

  • Data Definition Language (DDL)
    create table, drop table, etc
  • Data Manipulation Language (DML)
    select, insert, delete, update
  • Other Commands
    indexes, constraints, views, triggers, transactions, authorization, etc

Basic SELECT Statement

Select A1, A2, ..., An
From R1, R2, ..., Rm
Where condition

example

SELECT name FROM celebs; 
SELECT * FROM celebs;
SELECT DISTINCT age FROM celebs;
SELECT * FROM celebs WHERE age >= 20;
SELECT * FROM celebs WHERE name LIKE 'da_id';
SELECT * FROM celebs WHERE name LIKE '%vi%';
SELECT * FROM celebs WHERE name BETWEEN 'a' AND 'j';  -- name begin with [a, j)
SELECT * FROM celebs WHERE age BETWEEN 20 AND 30 AND name = 'david';
SELECT * FROM celebs WHERE age BETWEEN 20 AND 30 OR name = 'david';
SELECT * FROM celebs ORDER BY age DESC;
SELECT * FROM celebs ORDER BY age DESC, name;
SELECT * FROM celebs ORDER BY age ASC LIMIT 3;
SELECT S1.id, S1.name, S1.age, S2.id, S2.name, S2.age 
FROM celebs S1, celebs S2
WHERE S1.age = S2.age AND S1.id < S2.id;

集合操作

-- union
SELECT cName AS name FROM College
UNION 
SELECT sName AS name FROM Student

SELECT cName AS name FROM College
UNION ALL
SELECT sName AS name FROM Student
ORDER BY name;

-- intersect 
SELECT sID FROM Apply WHERE major = 'CS'
INTERSECT
SELECT sID FROM Apply WHERE major = 'EE'
-- 上面的 intersect 与下面的相等 (注意distinct)
SELECT DISTINCT A1.sID
FROM Apply A1, Apply A2
WHERE A1.sID = A2.sID AND A1.major = 'CS' AND A2.major = 'EE'

-- except
SELECT sID FROM Apply WHERE major = 'CS'
EXCEPT
SELECT sID FROM Apply WHERE major = 'EE'
-- 上面的 except 与下面的相等
SELECT sID
FROM Student
WHERE sID IN (SELECT sID FROM Apply WHERE major = 'CS')
AND NOT sID IN (SELECT sID FROM Apply WHERE major = 'EE')

Subquery

常会用到 IN, EXISTS, ALL, ANY

-- subquery in where
SELECT sName
FROM Student
WHERE sID = (
    SELECT sID 
    FROM Apply 
    WHERE cName = 'MIT' AND major = 'CS')

SELECT sName
FROM Student
WHERE sID IN (SELECT sID FROM Apply WHERE major = 'CS')

SELECT cName, state
FROM College C1
WHERE EXISTS (SELECT * FROM College C2      
              WHERE C2.state = C1.state AND C1.cName <> C2.cName)

SELECT cName 
FROM College C1
WHERE NOT EXISTS (SELECT * FROM College C2
                  WHERE C2.enrollment > C1.enrollment)

-- subquery in from
SELECT *
FROM (SELECT sID, sName, GPA, GPA*(sizeHS/1000.0) AS scaledGPA
FROM Student) G
WHERE ABS(G.scaledGPA - GPA) > 1.0;

-- subquery in select

JOIN

Join vs Subquery
semantic:

  1. Take cross-product
  2. Apply selection/condition
  3. Apply projection
-- cross join
SELECT DISTINCT s.sName, a.major
FROM Student s, Apply a
WHERE s.sID = a.sID

SELECT Apply.sID, sName, GPA, Apply.cName, enrollment
FROM Apply, Student, College
WHERE Apply.sID = Student.sID AND Apply.cName = College.cName

-- inner join on condition
SELECT DISTINCT sName, major
FROM Student JOIN Apply
ON Student.sID = Apply.sID

SELECT Apply.sID, sName, GPA, Apply.cName, enrollment
FROM (Apply JOIN Student ON Apply.sID = Student.sID)
JOIN College ON Apply.cName = College.cName

-- inner join using attrs
SELECT DISTINCT sName, major
FROM Student JOIN Apply using(sID);


-- outer join
-- Left, Right, Full Outer Join
SELECT sName, sID, cName, major 
FROM Student LEFT JOIN Apply using(sID)
-- outer join 可用下面的等效
SELECT sName, Student.sID, cName, major 
FROM Student, Apply
WHERE Student.sID = Apply.sID
UNION
SELECT sName, sID, NULL, NULL
FROM Student
WHERE sID NOT IN (SELECT sID FROM Apply);

Aggregation

注意 Aggregation 的操作顺序


Aggregation.jpg
Select A1, A2, ..., An
From R1, R2, ..., Rm
Where condition
Group By columns
Having condition

聚合函数只能用在 An 和 Having 的 condition 上
Group by 也可以用 nested query 实现,但 group by 更高效
注意 Where 中的 condition 与 Having 中的 condition 含义上的区别

-- Aggregate functions 
SELECT AVG(GPA)
FROM Student
WHERE sID IN (SELECT sID FROM Apply WHERE major = 'CS')

SELECT COUNT(*)
FROM College
WHERE enrollment > 15000;

SELECT COUNT(DISTINCT sID)
FROM Apply
WHERE cName = 'Cornell'

SELECT CS.avgGPA - NonCS.avgGPA
FROM (SELECT AVG(GPA) AS avgGPA FROM Student
      WHERE sID IN (
        SELECT sID FROM Apply WHERE major='CS')) AS CS,
     (SELECT AVG(GPA) AS avgGPA FROM Student
      WHERE sID NOT IN (
        SELECT sID FROM Apply WHERE major='CS')) AS NonCS

SELECT cName, COUNT(*)
FROM Apply
GROUP BY cName;

SELECT cName
FROM Apply
GROUP BY cName
HAVING COUNT(*) < 5;

SELECT DISTINCT cName
FROM Apply A1
WHERE 5 > (SELECT COUNT(*) FROM Apply A2 WHERE A2.cName = A1.cName)

SELECT cName, major, MIN(GPA), MAX(GPA)
FROM Student, Apply
WHERE Student.sID = Apply.sID
GROUP BY cName, major;

SELECT MAX(mx-mn)
FROM (SELECT cName, major, MIN(GPA) AS mn, MAX(GPA) AS mx
    FROM Student, Apply
    WHERE Student.sID = Apply.sID
    GROUP BY cName, major) M;

NULL

-- null value
SELECT sID, sName, GPA
FROM Student
WHERE GPA > 3.5 OR GPA <= 3.5 OR GPA IS NULL;

Data Modification Statements

Insert

INSERT INTO Table
    Values(A1, A2, ..., An)
INSERT INTO Table
    Select-Statement

-- example
INSERT INTO Apply
SELECT sID, 'Carnegie Mello', 'CS', null
FROM Student
WHERE sID NOT IN (SELECT sID FROM Apply);

Update

Update Table
Set Attr = Expression
Where Condition

-- example
UPDATE Apply
SET decision = 'Y', major = 'economics'
WHERE cName = 'Carnegie Mellon'
    AND sID IN (SELECT sID FROM Student WHERE GPA < 3.6);

UPDATE Student
SET GPA = (SELECT MAX(GPA) FROM Student),
    sizeHS = (SELECT MIN(sizeHS) FROM Student);

Delete

Delete From Table
Where Condition

-- example
DELETE FROM Student
WHERE sID IN (
        SELECT sID
        FROM Apply
        GROUP BY sID
        HAVING COUNT(DISTINCT major) > 2);

DDL

DROP TABLE IF EXISTS Movies;
DROP TABLE IF EXISTS MovieStar;

CREATE TABLE Movies (
    title      CHAR(100),
    year       INT,
    length     INT,
    genre      CHAR(10),
    studioName CHAR(30),
    producer INT,
    PRIMARY KEY (title, year)
);

CREATE TABLE MovieStar (
    name       CHAR(30) PRIMARY KEY,
    address    VARCHAR(255),
    gender     CHAR(1) DEFAULT '?',
    birthdate  DATE
);



ALTER TABLE MovieStar ADD phone CHAR(16) DEFAULT 'unlisted';

ALTER TABLE MovieStar DROP birthdate;

SQL 做查询时,只要按照它的要求,根据顺序一步一步写就行了

sql.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,271评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,275评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,151评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,550评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,553评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,559评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,924评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,580评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,826评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,578评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,661评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,363评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,940评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,926评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,872评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,391评论 2 342

推荐阅读更多精彩内容