常见SQL

作者: 乐百事52淑熙 | 来源:发表于2017-07-05 17:00 被阅读0次

    注意:以下sql以oracle为基础,有些sql可能与Mysql,Access,DB2有些差异。

    创建数据库 database:create database databasename

    创建数据库表 table:create table tablename(

                              column_name1  data-type,

                              column_name2  data-type,

                              ......

    )

    创建索引 index:create index index_name on table (columnname)

    创建视图 view:create view view_name as select column from table

    获取表述所有数据:select * from table

    获取表中某列数据: select column_name from table

    获取表中不重复的值 distinct:select distinct column_name from table

    按某种条件查询数据 where:select * from table where condition

    多种条件 and & or :select * from table where condition1 and/or condition2

    排序 order by : select * from table order by column_name asc/desc

    插入 insert into : insert into table values( value1,values2,...) 或者

                       insert into table(columns_name1,column_name2,...)values(value1,value2,...)

    修改 update: update table set column_name = value where column_somename = somevalue

    删除 delete: delete from table where column_name = value

    删除 truncate: truncate table table_name (数据量较大时,只删除表中数据,truncate性能更好)

    获取前n条数据: select * from table where rownum <= n

    模糊查询 like: select column_name from table_name where column_name like condition  (

    条件中可以使用通配符:1、%  替代一个或者多个字符;2、_  替代一个字符;3、[charlist]  字符列中任一字符;4、[^charlist]或者[!charlist]  不在字符列中的任一字符)

    条件操作符 in: select * from table where column in (value1,value2,...)  (相当于连续几个and where)

    获取范围数据 between:select * from table where column between a and b

    别名 Alias : select * from table as alias_name (表的别名)

                       select column_name as alias_name from table (列的别名)

    连接 join : inner join 内连接  取左右表共同都有的  left join 左连接 取左表有的  right join 右连接 取右表有的  full join 全连接  取左右表全部

    union (union all) :select column_name1 from table1 union(union all) select column_name2 frome table2   (union联合两个select时结果无重复值,union all 联合两个select时结果可以有重复值)

    select into :select * into table_backup from table (多用于备份)

    约束 constraints: not null  (不为空) unique (唯一值)  primary key (主键)  foreign key(外键)  check(检查值的范围)  default (默认值)

    drop :drop index (table/database) name

    alter table :增加/修改/删除表中的列

    || : sql连接符 即 "AB" || "CD" 就是 "ABCD"

    :=  :变量赋值操作符

    分组:select count(*) ,t.a ,t.b from table t group by t.a,t.b; 将表数据按a,b分组。

    取出分组中数量小于10的数据:select count(*) ,t.a ,t.b from table t group by t.a,t.b having count(*)< 10;一条语句,相比子查询要好些。

    推荐微信公众号【排骨肉段】,记录日常的美好。

    相关文章

      网友评论

          本文标题:常见SQL

          本文链接:https://www.haomeiwen.com/subject/qutxhxtx.html