• SQL使用范例


    本论文是我看过的一本书叫《SQL基础教程》的笔记,当时记在了本子上,现在本子估计大限将至,所以转存在博客里,都是SQL的基础使用,以供复习和参考之用。

    首先讲述常见数据库的命令行方式连接:

    SQL Server 2000  >osql -E -d dbname

    SQL Server 2005/2008 > sqlcmd -d dbname

    oracle> sqlplus user/password@dbname

    DB2> db2 connect to dbname

    MySQL>mysql -h host -u user -p dbname

    PostgreSQL>psql -h host -u user -w dbname 

    SQL使用 -- 作为行注释,/*  */ 作为多行注释

          一、检索数据

    1.select选择操作 

    标准模式为: select [all] coumns from tables

    [join joins] 

    [where search_condition] 

    [group by grouping_columns] 

    [having search_condition] 

    [order by sort_column]  [ASC | DESC]

      2.使用 AS 创建列的别名   column as alias_name ,......

    3. 使用distinct 消除重复行  select distinct columns ......

    4.使用order时可以按多列排序,按列相对位置排序   order by 4 asc ,2 desc....

    select title_id,type,price,sales from titles order by case when type='history' then price else sales end

    select title_id,price,sales,price*sales as "Revenue" from titles order by "Revenue" desc

      5.where筛选行

    在where中常使用 like ,between ,in ,is null ,不可使用聚合函数 sum(),count();不可用别名比较

        where pubdate >= DATE '2001-01-01';

           select sales as copies_sold from tites where copies_sold > 1000

    ——> select * from (select sales as copies_sold from titles ) ta where copies_sold > 1000 

    6.使用三值逻辑(3VL) and,or,not组合

    and不需要加括号,or需要加括号,not的正确写法是 not  state='CA'

    select type,type='history' as "hist?",type ='biography' as "bio?", price , price<20 as "<20?" 

      7.like匹配模式(not like)

    % 0或者多,_ 任意一个,like的使用需要加上单引号 '

    select columns from table where test_column [not] like 'pattern' escape "escape_char"; 

      8.between and  , in , in null

    where test_column between low_value and hign_value 

    where test_column in (value1,value2,value3)

    where test_column is [not] null

            二、操作符和函数

    源自列的值、由系统确定的值、常数和其他数据的结果,可以执行如下运算:算术运算,字符串运算,日期和时间运算,系统运算。

    1.创建派生列

    select 2+3select au_id,2+3 from authors;

    select title_id,price,0.10 as "discount",price*(1-0.10as "new price" from titles;

    2.执行算术运算 + - * /

    select title_id , - advance as "advance" from royalties;

    3.确定计算顺序,算术操作符(+,-,*等) 的优先级高于比较操作符(<,=,>等),比较操作符的优先级高于逻辑操作符(not,and,or).

    4.使用 || 连接串

    select au_fname || '' || au_lname as "author name" from authors order by au_lname asc, au_fname asc;

    select cast(sales as char(7)) || ' copies sold of title ' || title_id as "biography sales" from titles where type ='biography' and sales is not null order by sales desc; 

      5.使用substring()提取子串

    select pub_id,substring(pub_id from 1 for 1as "alpha part",substring(pub_id from 2as "num part" from publishers;

    6.upper()和lower()更改串的大小写

    select title_name from titles where upper(title_name) like '%M0%'; 

    7.使用trim()修整字符

    trim ([[leading | trailing | both] from ]  string) leading删除前导空格,trailing删除尾随空格,定义both同时删除前导和尾随空格,如果不指定,默认为both

    8.使用character_length()得到串的长度   character_length(string)

    9.使用position()查找子串   position(substring in string)

    select au_fname,position('e' in au_fname) as "pos e" from authors;

    10.执行日期及时间间隔运算

    提取日期或时间间隔的一部分:extract(field from datetime_or_interval),field 为year,month,day,hour,minute,second,timezone_hour,timezone_minute.

    当前日期:current_date    当前时间:current_time     当前的时间戳:current_timestamp

    当前用户信息:current_user

    11.使用cast()转换数据类型  cast(expr as data_type)

    12.使用case()计算条件值

        case comparison_value 

       when value1 then result1
       when value2 then result2
       ......
       when valueN then resultN
       [else default_result]

    end 

      coalesce()检查空值:coalesce(expr1,expr2,expr3)   如果expr1不为空返回exp1,依次规律顺序计算 

    nullif() 表达式 : nullif(expr1,expr2)  如果expr1与expr2相同,则返回null,否则返回 expr1 

      三、汇总和分组数据

    在此讲述的一组值进行操作以产生一个汇总值,这种函数称为聚合函数或集合函数,聚合函数只返回单一的统计值。聚合函数不能出现在where子句中,不可在select子句中使用混合使用聚合和非聚合表达句,但分组列例外,不可嵌套使用,但子查询可以使用聚合,聚合不可使用子查询。

    常见的聚合函数:min(expr),max(expr),sum(expr),avg(expr),count(*),count(expr),sum(distinct expr), func([all | distinct ] expr)

    四、联结

    从多个表中提取数据。

    交叉联结:返回第一个表的每一行和第二个表的所有行组合得到的表的所有行

    自然联结:对第一个表的所有列和第二个表具有相同名字的列进行等同比较的联结

    内联结:使用比较操作符基于每一个表中共同列的值,匹配源自两个表的行。内联结是最普通的联结类型

    左外联结:返回左表中的所有行,不管与右表是否有匹配的联结列。如果左表中的行在右表没有匹配的行,关联的结果对于右表的所有select子句列包含空值

    右外联结:与左外联结想法。返回右表中的所有行。如果右表中的行没有匹配左表的行,则对于坐标返回空值

    全外连接:返回左表好右表的所有的行。若果一行在另一表中没有匹配行,另一表的select子句列包含空值。如果两个表之间匹配,则整个结果行包含两个表中的值。

    自联结: 表和它自身联结

    select au_fname,au_lname,a.city from authors a inner join publishers p on a.city=p.city 

    select au_fname,au_lname,a.city from authors a , publishers p where a.city =p.city 

    交叉  select column from table1 cross join table2 

    select au_id,pub_id,a.state as "au_state",p.state as "pub_state" from authors a ,publishers p;

    也可以使用    using()  替代 on xx = yy;

    自然    select columns from table1 natural join table2 where xx = yy ...join_conditions 

      内       select columns from table1 inner join table2 on .. inner join .. on .. inner join .. on .. where ... and ...

    外       select columns from left_table left(outerjoin right_table on join_condition 

    自       select columns from table as alias1 inner join table as alias2 on join_condition

    五、子查询

    select pub_name from publishers where pub_id in (select pub_id from titles where type = 'biography')

    常在子查询中的使用not  in,not exists等,内联结都可写作子查询,但反过来就不行。外联结都可以写成子查询,尽管外联结不是可交换的。 

      简单子查询select au_id,city from authors where city in (select city from publishers);

    相关子查询

      select outer_columns from outer_table where outer_column_value in (select inner_column from inner_table where inner_column = outer_column)

    子查询如果结果中出现了空值,会有意外结果,因此要确保正确使用

    1.子查询作为列表达式

    select max(ta.count_titles) as "max titles" from (select count(*as count_titles from title_authors group by au_id) ta;

    select t1.title_id,t1.sales, (select sum(t2.sales) from titles t2 where t2.title_id <= t1.title_id) as "running total" from titles t1; 

             select au_id,au_fname,au_lanme,state from authors where state=(select state from publishers where pub_name = 'tenterhooks press');

      2.使用in,all,exists限定条件

    where test_expr op (subquery)

    having test_expr op (subquery)
     where (subquery) op (subquery)
     where test_expr [not] in (subquery)
    having test_expr [not] in (subquery)
     where test_expr op all (subquery)
    having test_expr op all (subquery)
     where [not] exists (subquery)

      having [not] exists (subquery) 

       < all (subquery)  ->   < min(subquery values)

    > all (subquery)  ->    > max(subquery vlaues)

    < any (subquery)  ->   < max(subquery values)

    > any (subquery)  ->   > min(subquery values)

    in = any , not in = <> all  (not <> any) 

    例子:   select distinct a.au_id from authors a inner join title_authors ta on a.au_id = ta.au_id; 

      ——>  select distinct a.au_id from authors a , title_authors ta where a.au_id = ta.au_id;

      select au_id from authors a where au_id in (select au_id from title_authors);

    ——>  select au_id from authors a where au_id = anyselect au_id from title_authors);

    select au_id from authors a where exists (select * from title_authors ta where a.au_id = ta.au_id); 

    ——>  select au_id from authors a where 0 < (select count(*from title_authors ta where a.au_id = ta.au_id); 

      六、集合操作

    对提取的结果进行操作,并集(union),交集(intersect),差集 (except)

    select state from authors union (allselect state from publishers  (all 表示不删除重复的部分)

    select city from authors intersect /except select city from publishers;

    七、Insert,Update,Delete

    insert into table values (value1,value2,...,valueN);

    insert into table (column1,column2,..) values (......);

    insert into table [(column1,column2,...,columnN)] subquery;

    update table set column = expr[where search_condition];

    delete from table [where search_condition]; 

     八、创建,更改和删除

    1.create table_name

    {
          column1 datatype1 [col constraints1],
           ....
           columnN datatypeN [col constraintsN]

    } 

    对于约束可以直接写在列定义的后面,也可以建立一个约束,建立约束的方法:  constraint constraint_name;

    如:constraint publishers_pk primary key(pub_id); 

         constraint royalties_title_id_fk foreign key(title_id) references titles (title_id);

    而对于受外键约束的列,当主键删除或更新时,列的操作可以定义如下:

    on update | delete [cascade | set null | set default | no action] 

    对列的约束有以下几种:not null, primary key , foreign key, unique, check, default

    如: constraint title_id_chk check (substring (title_id from 1 for 1 ) = 'T') ;

    2.create temporary table 创建临时表:

    create {local | global} temporary table table_name(); 

    create table as   利用已存在的表创建新表:
      create table new_table as subquery;

      create table authors2 as select * from authors;

    create table publishers as select * from publishers where 1=2;

    3.alter table table_name alter_action:

    >alter table authors add email_address char(25);

    >alter table authors drop column email_address; 

    注意alter改变的是表的结构,update改变的是表的内容,若只是想把表清空,并不想删除,则可以使用 truncate: truncate table table_name; 

      九、创建索引、视图

    create [unique] index index_name on table (index_columns);

    创建索引,加快数据检索速度,所以是排序的列表。

    create view view_name [(view_columns)] as select_statement; 

    视图是存储的select语句,简化数据访问,自动更新,增强安全性,逻辑上数据独立。视图存在于SQL语句的生存期,临时表存在于进程的生存期。

    十、事务

    事务的控制:commit,savepoint,rollback,set transaction

    显示提交或回滚: >commit; /  >rollback; 

    设置自动提交: > set autocommit on;

    退回指定点:     > rollback [work]  to [savepoint];

  • 相关阅读:
    C++ quick sort ascendingly and descendingly
    C++ write file and read file via fstream
    C++ optimized fibonacci algorithm
    C++ compute quick sort time cost via std::chrono which its precision can reach nanoseconds
    C++ selection sort.quick sort
    C++ quick sort
    C++ in ubuntu pop up message via notifysend command . zenity command
    C++ vector iterator std::ref(vec)
    C++使用new来创建动态数组
    C++ 使用new来分配内存
  • 原文地址:https://www.cnblogs.com/kingcucumber/p/2964695.html
Copyright © 2020-2023  润新知