sql语言
DDL与DML
DDL: maintaining structure of database. (CREATE, DROP, ALTER, RENAME)
DML: maintaining contents of database. (SELECT, INSERT, DELETE, UPDATE)
sql language:
INSERT
注:字符为单引号
INSERT INTO tablename {column1,column2,…}values(exp1,exp2,…);
//插入
DELETE
UPDATE
CREATE
CREATE的时候,先CREATE没有外键的表,最后CREATE有外键的表
假设我们有一个主键列为ID的表,表中有字段k,并且在k上有索引。这个表的建表语句是:
1 | create table T ( |
DROP
DROP的时候,先DROP有外键的表,最后DROP没有外键的表
ALTER
例如增加一列
RENAME
语法顺序与执行顺序
相当于就是 SELECT [DISTINCT] 的顺序换了一下。
Aggregate Functions
操作符
找最大值
例一:哪一个物品有最高的cost?
If two different items have highest price, 第一个query会把两个都返回,第二个query只会返回一个
例二:找出有最多空房间的楼层
http://sqlfiddle.com/#!9/492887/22
1 | SELECT |
注:以下写法错误:
1 | SELECT BlockFloor, COUNT(*) AS "maximum number of rooms available" |
例三:找出第二高的薪水
https://leetcode.com/problems/second-highest-salary/
如何避免有多个最大值的情况:使用DISTINCT:Sort the distinct salary in descend order,再用LIMIT和OFFSET
1 | -- 法一:Using sub-query and LIMIT clause |
注:如果直接写:
1 | SELECT DISTINCT |
this solution will be judged as 'Wrong Answer' if there is no such second highest salary since there might be only one record in this table.
例四:找出每门课分数都大于75的学生中,分数最高的那条记录
http://sqlfiddle.com/#!9/ee6ee5/1
输出:
1 | SELECT * |
(👆不确定是否是正确答案)
注:
1 | SELECT max(Score) |
输出的结果是满足条件的每个学生各自的最高分数:
所以以下写法错误:
1 | SELECT * |