分别整理常用mysql和oracle的基本sql语句包括DML、DDL、DCL

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33243189/article/details/88363141

DML(data manipulation language)数据操纵语言,包括:select、insert、update、delete。

DDL(data definition language)数据库定义语言,包括:create、alter、drop等,改变数据库表结构的操作。

DCL(Data Control Language)数据库控制语言,包括:grant,deny,revoke等操作。

ORACEL
    建表sql:
    create table tableName(
        id varchar2 primary key,
        name varchar2 not null
        ...);
    复制表
    create table dept1 as
    select columnName1,columnName2...
    from dept2;
    添加表注解
    comment on table tableName is '';
    添加字段注解
    comment on column tableName.columnName is '';
    添加字段 
    alter table tableName add(columnName dataType [default value] [NULL /not null], );多行可以,隔开
    修改字段
    alter table tableName modif(columnName dataType [default value] [not null/]);
    删除字段
    alter table tableName drop(columnName);
    表重命名
    alter table tableName rename to newTableName;
    修改列名
    alter table tableName rename column columnName to newColumn;
    
    新增数据
    insert into tableName
    (columnName1,columnName2...)
    values
    (value1,value2);
    批量新增数据
    insert ALL 
    into tableName(columnName1,columnName2...)values(value1,value2...)
    into tableName(columnName1,columnName2...)values(value1,value2...)
    into tableName(columnName1,columnName2...)values(value1,value2...)
    ...
    select 1 from dual;
    删除数据
    truncate table tableName;
    delete from tableName where 1=1;
    在存储过程中默认是不允许执行truncate table tablename操作的,所以要使用
    execute   immediate 'truncate table tablename';
    修改数据
    update tableName ;
    set 
    columnName1 = value1,
    columnName2 = value2...
    where 1=1;
    查询数据
    select * from tableName;
    占位查询,查询5个字母,第二个是o
    select * from tableName where columName like '_0___';
    去重可以用group by id
    添加转换
    select (case gender when 0 then '男' when 1 then ‘女’ end  ) gender from ss;
    分页查询
    select TT.*(
        select A.*,ROWNUM RN
        from (SELECT * FROM TABLE_NAME) A  WHERE ROWNUM <= 10) TT
    WHERE RN > 0;
    查看表注解
    select table_name,table_type,comments 
    from user_tab_comments 
    where table_name = tableName;
    查看字段注解
    select table_name,column_name,comments 
    from user_col_comments 
    where table_name = tableName;
    获取表的所有字段
    select * from user_tab_columns where Table_Name= tableName; //用户
    select * from all_tab_columns where Table_Name= tableName;//多了ower 所有者
    select * from dba_tab_columns where Table_Name= tableName;//多了ower 所有者
    查看所有表
    select table_name from user_tables; //当前用户拥有的表      
    select table_name from all_tables; //所有用户的表 
    select table_name from dba_tables; //包括系统表
    select table_name from dba_tables where owner='用户名';
    查看所有表空间
    select * from user_tablespaces;
    select
        b.file_name 物理文件名,
        b.tablespace_name 表空间,
        b.bytes/1024/1024 大小M,
        (b.bytes-sum(nvl(a.bytes,0)))/1024/1024 已使用M,
        substr((b.bytes-sum(nvl(a.bytes,0)))/(b.bytes)*100,1,5) 利用率
    from dba_free_space a,dba_data_files b
    where a.file_id=b.file_id
    group by b.tablespace_name,b.file_name,b.bytes
    order by b.tablespace_name;
    
    常用的函数
    绝对值:abs(-1) -> 1
    取整函数(大):ceil(-2.2) -> -2
    取整函数(小):floor(-1.1) -> -2
    取整函数(截取):trunc(-2.3) -> -2
                   trunc(to_number('0123.123'),2) -> 123.12
    四舍五入:round(3.42718,4) -> 3.4272
    取平方:power(4,2) -> 16
    去平方根:sqrt(16) -> 4
    随机数:dbms_random.value() -> 0-1之间
    随机数:dbms_random.value(2,4) -> 2-4之间
    取最大值:greatest(-1,21,35,66) -> 66
    取最小值:least(-1,21,35,66) -> -1
    空值替代值: nvl(null,0)
    时间转字符串处理:to_char(sysdate,'yyyy-mm-dd hh24:mi:ss')
    时间转字符串处理:to_char(sysdate,'day') week
    字符串转时间处理:to_date('2018-10-11 16:12:12','yyyy-mm-dd hh24:mi:ss')
    月份间隔:select months_between(to_date('03-31-2014','MM-DD-YYYY'),to_date('12-31-2013','MM-DD-YYYY')) MONTHS
             FROM DUAL; 
    字符串截取:substr('ABC',a,b) 当a等于0或1时,都是从第一位开始截取,b是截取总长度
               substr('HELLO WORD',-1,3) -> D 
               substr('HELLO WORD',-4,3) -> WOR 
               (注:虽然7、8、9、10截取的都是3个字符,结果却不是3 个字符; 只要 |a| ≤ b,取a的个数(如:7、8、9);当 |a| ≥ b      时,才取b的个数,由a决定截取位置(如:9和10))
    查找子字符:instr( string1, string2 [, start_position [, nth_appearance ] ] )   /   instr(源字符串, 目标字符串, 起始位置, 匹配序号)
               instr('ABCDEF','CD') -> 3  
               instr('ABCDEFCD','C',2,3)  -> 7 从第2(B)号位置开始找第3次出现的'C'
    连接字符串:'Hello'||'World' concat -> HelloWorld
    去除空格键:trim('  wish  ') -> wish
    去除后空格键:rtrim('wish  ') rtrim -> wish
    去除前空格键:ltrim('  wish') ltrim -> wish
    字符串长度:length('ABC') -> 3
    大写:UPPER('abc') -> ABC
    小写:LOWER('ABC') -> abc
    大小写互换:initcap('wish')
    替换:replace('ABCDEF','A','a') -> aBCDEF
    连接字符串:concat('A','B') -> AB
    转数字:to_number('021') -> 21
           to_number('120.11','999.99') -> 120.11
    合计:count(1) 效率最高
         count(distinct score)
    平均值:avg(distinct|score)
    最大值:MAX()
    最小值:MIN()
    总和:SUM(SCORE)

    新建存储过程
    create [or replace] procedure procedureName
        (paramName1 in dataType,paramName1=2 in dataType,...)
        as
        declare variableName variableType := val;//变量定义并赋值
        begin
        ...
        end
    执行存储过程
    exec procedureName(val1,val2...)
    判断分支if
    if 表达式[X=1] then
        begin
        ...
        end;
    elsif 表达式[x=2] then
        begin
        ...
        end;
    else 
        ...
    end    if;
    循环for X in ... LOOP
    for i in 1..10 loop
        ...
    end loop;
    循环while
    while 表达式[x>0] loop
        ...
    end loop;
    新建函数
    create or replace functon functionName(paramName1 dataType,...)
    return returnDataType
    is
    toParamName returnDataType;//这边可以定义变量
    begin
    ...
    return toParamName;
    end;
    删除函数
    drop function functionName;
    新建触发器
    create or replace trigger triggerName before|after insert|update|delete(insert or update or DELETE)
    on tableName for each row //每行都触发执行
    begin
    ...
    end

mysql
    建表
    create table tableName(
        columnName dataType primary key COMMENT '',
        //添加主键 primary key (id)
    )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT tableComment;
    查看当前数据库
    select database();
    获取当前数据库表
    SELECT *
    FROM information_schema.TABLES 
    WHERE TABLE_SCHEMA = (select database())
    AND TABLE_NAME = tableName
    获取当前数据库表字段信息
    SELECT *
    FROM information_schema.Columns 
    WHERE TABLE_SCHEMA = (select database())
    AND TABLE_NAME = 'hpc_data_monitor';
    新增字段
    alter table tableName add columnName dataType not null comment '';
    删除字段
    alter table tableName drop column columnName;
    修改字段
    alter table tableName modify columnName dataType not null comment '';
    修改一个字段名称,并重新指定字段类型
    alter table tableName CHANGE oldColumnName newColumnName int;
    新增数据
    insert into tableName (columnName1,columnName2...)
    values
    (value1,value2..);
    批量新增数据
    insert into tableName (columnName1,columnName2...)
    values
    (value1,value2..),
    (value1,value2..),
    (value1,value2..)...;
    更新数据
    update tableName 
    set columnName1 = value1[, columnName2 = value2...]
    where ;
    删除数据
    delete from tableName where 1=1;
    truncate table tableName;
    分页查询
    select * 
    from tableName
    limit 10,10(查询11~20)
    
    常用函数
    取绝对值: ABS(-1) -> 1
    取余: mod(10,7)/10%7 -> 3
    向下取整:floor(3.2) -> 3
    向上取整:ceiling(2.1) -> 3
    四舍五入取整:round(1.69) -> 2
    字符串连接:concat(str1,str2...) //如果有一个参数是null,则返回null
    字符串长度:length(str)
    查找字符串:LOCATE(substr,str):返回子串substr在字符串str第一个出现的位置,如果substr不是在str里面,返回0. locate('ab','hoab') -> 3
    查找字符串:instr(str,substr):返回子串substr在字符串str第一个出现的位置,如果substr不是在str里面,返回0. instr('hoab','ab') -> 3
    返回字符串最左面的字符串:left(str,5) 返回从1开始到5位置的字符串 left('abcdef',2) -> ab
    返回字符串最右面的字符串:right(str,5) 返回从-5开始到-1位置的字符串 right('abcdef',2) -> ef
    截取字符串:substring(str,5) 从起始位到第5位字符串 substring('abcdef',2) -> ab
    去空前后空格:trim(str)
    去前空格:ltrim(STR)
    去后空格:rtrim(str)
    替换字符串:replace(STR,from_c,to_c) replace('ABCDAF','A','a') -> aBCDaF
    INSERT(str,pos,len,newstr):返回字符串str,在位置pos起始的子串且len个字符长的子串由字符串newstr代替。INSERT(‘whatareyou', 5, 3, ‘is') -> whatisyou 
    时间日期
    根据时间返回星期(1=星期天,2=星期一, …7=星期六)
    DAYOFWEEK('1998-02-03')-> 2
    根据时间返回日期,在1到31范围内。 
    DAYOFMONTH('1998-02-03')-> 3
    根据时间返回日期,在1到366范围内
    DAYOFYEAR('1998-02-03') -> 34
    返回date的月份,范围1到12
    MONTH('1998-02-03') -> 2
    返回年月日YYYY-MM-DD或YYYYMMDD
    CURDATE();
    返回时分秒HH:MM:SS或HHMMSS
    CURTIME();
    返回YYYY-MM-DD HH:MM:SS或YYYYMMDDHHMMSS
    now();
    时间格式化
    DATE_FORMAT(NOW(),'%Y %m %d %H:%i %S')  -> 2019 03 08 15:16 11
    FROM_UNIXTIME(1344887103,'%Y-%m-%d %H:%i:%S') 2012-08-14 03:45:03
    字符串转时间
    str_to_date('2012-08-14 03:45:03', '%Y-%m-%d %H:%i:%S') 2012-08-14 03:45:03
    时间转时间戳
    unix_timestamp(now()) 1552029574
    unix_timestamp('2012-08-14 03:45:03') 1344887103
    条件判断
    select case status when 1 then 'one' 
                       when 2 then 'tow' 
                       else 'more' end;
    IF(expr1,expr2,expr3) expr1返回true,则返回expr2,否则返回expr3
    Strcmp(str1,str2):如果str1>str2返回1,str1=str2反回0,str1<str2返回-1)

    高效分页查询利用主键索引
    select * from tableName t 
    join (select id aId from tableName order by id limit 100000,20)a  //order by 使用其他字段索引失效
    on a.aId = t.id

部分后续整理添加。

猜你喜欢

转载自blog.csdn.net/qq_33243189/article/details/88363141