《SQL 必知必会》学习笔记

2,411 阅读3分钟
原文链接: www.jianshu.com

基本常识

去掉返回结果空格


两边都去掉:TRIM

去掉左边:LTRIM

去掉右边:RTRIM

Union


默认,Union从查询结果集中自动去除重复的行,如果想返回所有匹配的行,用Union ALL。如果需求是后者,即确实需要每个条件的匹配行全部出现(包括重复行),则必须使用Union ALL而不是WHERE。

对组合查询结果排序
在用Union组合查询时,只能使用一条Order By子句,它必须出现在最后一条SELECT语句之后。并且,它将用来排序所有SELECT语句返回的所有结果,而不仅仅是就近原则

主键和Null值


只有不允许Null值的列可用于主键,允许Null值的列不能用于主键。

添加/删除主键


添加:
alter table add primary key({columnName});

删除:
alter table drop primary key({columnName});

更新表


增加列
alter table {tableName} add {columnName};

删除列
alter table {tableName} drop column {columnName};

P.K.

拼接字段


Oracle:||

MySQL:concat

substr 和 Left/Right


截取某字段左右字符

Oracle:substr

MySQL:Left/Right

创建/插入/查询'YYYY-MM-DD HH:MM:SS'时间类型的字段


example:2017-04-22 20:01:02

创建

MySQLcreate table time (id int not null,time datetime);

Oracle:create table timetable(id int not null,time2 date);(表名和时间字段名称不能为time,MySQL可以;字段类型MySQL是datetime,Oracle是date)

插入

MySQL:
insert into time values(1,'2017-04-22 20:01:02');

Oracle:
insert into timetable values(1,to_date('2017-04-22 20:01:02','yyyy-MM-dd hh24-mi-ss'));

查询
以查询2017年份为例

MySQL:
select time from time where year(time) = '2017';

Oracle:
select time2 from timetable where to\_number(to_char(time2,'YYYY'))='2017';

别名


MySQL:
select test as test1 from test;(通过as即可将test转换为别名test1)

Oracle:
select test test1 from test;(Oracle中没有as,所要定义的别名直接跟在原有的后面即可)

查看创建表的语句


MySQL:
show create table {tableName};

Oracle:

a.PL/SQL developer:表名->右击->查看->查看SQL

b.SQL语句select * from TEST tselect dbms_metadata.get_ddl('TABLE',{tableName}) from dual;

重命名表名


MySQL:
rename table {tableName} to {newTableName};

Oracle:
rename {tableName} to {newTableName};

Oracle较MySQL在rename后无需table(PL/SQL Developer连接)

外键


example:让table2中的主键cus_id作为table1中字段cus_id的外键
MySQL:
create table {table1} (id int not null primary key,cus_id int not null,foreign key(cus_id) references {table2}(cus_id);

以上的写法是MySQL的表级约束,MySQL还提供了列级约束,但列级约束的外键约束并不会真正生效。
详情请戳这->mysql 设置外键约束(foreign key)

Oracle:
create table {table1} (id int not null primary key,cus_id int not null references {table2}(cus_id);
耐人寻味地是,MySQL中列级约束的写法在Oracle中可以完美实现外键约束的功能。

好图集锦

1. 常用文本处理函数


常用文本处理函数

2. 常用算术处理函数


常用算术处理函数

3. Group By 必知必会


Group By 必知必会01

Group By 必知必会02

Group By 必知必会3

4. Insert 必知必会


Insert 必知必会01

Insert 必知必会02

5. 复杂表结构更改步骤


复杂表结构更改步骤01

复杂表结构更改步骤02

6. 视图必知必会


为什么我们要使用视图?01

视图创建常见规则和限制01

视图创建常见规则和限制02

7. 为什么要使用存储过程?


为什么要使用存储过程?

8. 主键必知必会


主键必知必会

9. 外键的好处以及唯一约束


外键的好处以及唯一约束

10. 索引创建必知必会


索引创建必知必会

11. 触发器必知必会


触发器必知必会01

触发器必知必会02

触发器必知必会03

12. 数据类型必知必会


数据类型必知必会01

数据类型必知必会02