版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、第四章 SQL引言 IBM SYSTEM R SEQUEL ANSI 规范 SQL 1990 ISO 规范 SQL 1992 SQL3 (SQL99)体系构造 View Table File SQL DDL 包括完好性与平安性 DML SQL DDL 需求创建的构造 Table View Index Create table, view, index E.g. Create Table DEPT ( DEPT# Number, DNAME Char(5), Budget Number( 7,2);SQL DDL 续 索引 Create index on ( ) E.g. Create inde
2、x I1 on EMP (E#); Create index I2 on EMP (Ename); 独一性索引 E.g. Create unique index I1 on EMP (E#); SQL DDL 续 聚集索引 元组按照索引值顺序,物理上尽能够的存储在一同 , 在索引值上执行扫描scan操作时可以减少 I/O. E.g. Create cluster index CI1 on EMP (E#);根本查询块 典型的 SQL 查询语句格式:select A1, A2, ., Anfrom r1, r2, ., rmwhere P Ais 代表属性 ris 代表关系 P 是谓词.Sele
3、ct 子句 select 短语用于列出一切要查询的结果属短语用于列出一切要查询的结果属性性. 例如查找例如查找 DEPT 关系中一切部门名字关系中一切部门名字select dnamefrom DEPT 留意留意: SQL 大小写无关大小写无关Select 子句-续 SQL 的查询结果中允许有反复. 运用 distinct 消反复. 例如:查找 DEPT 关系中一切不同名的部门名字select distinct dnamefrom DEPTSelect 子句-续 select 短语中可以包含 数学表达式 . 例如: select S#, Sname, Status 2from S.Where 子
4、句 where 短语由给出谓词,其谓词由出如今短语由给出谓词,其谓词由出如今from 短语中的关系的属性组成短语中的关系的属性组成. 查找一切居住在查找一切居住在 London 并且形状大于并且形状大于 20的供应商的供应商号的供应商的供应商号select S# from Swhere city=London AND status 20 比较操作结果可以用逻辑操作比较操作结果可以用逻辑操作 and, or, 和和 not相连相连.Where 子句-续 between 比较操作. 查找形状在 20 和 30 之间的供应商的商号(也就是说要, 20 并且 30)select S#from S wh
5、ere status between 20 and 30From 子句 from 短语列出的关系在执行时要被扫描. 查找 employee department的结果 select from EMP, DEPT where emp.D#=dept.D#重命名操作 SQL 运用别名 alias name对关系和属性重命名:old-name new-name 查找一切供应商的名字、商号和形状; 将 S# 重命名为 number、将 sname 重命名为 nameselect sname name, s# number, statusfrom S元组变量 from 短语运用别名定义元组变量短语运用别
6、名定义元组变量. 查找一切已供应零件的供应商名字和零件号查找一切已供应零件的供应商名字和零件号. select sx.sname, spx.P# from S sx, SP Spx where sx.S#=spx.s#串操作 SQL 含有串匹配操作. 末拌有两个特殊的符号描画: %. 代表恣意长的子串. _. 代表恣意的单字符. Find the names of all suppliers whose city name includes the substring “Main.select snamefrom s where city like %Main%串操作-续 SQL 包括其他串操
7、作例如 concatenation (using “|) converting from upper to lower case (and vice versa) finding string length, extracting substrings, etc.排序 List in alphabetic order the names of all suppliers locating in London cityselect distinct snamefrom Swhere city=Londonorder by sname desc 表示降序, asc 表示升序;缺省时升序 E.g.
8、order by sname desc集合操作 union, intersect, 和 except 集合操作自动消反复集合操作-续 Find all cities where have a supplier, a part, or both:(select city from S)union(select city from P) Find all cities where have both a supplier and a part.(select city from S)intersect(select city from P) Find all cities where have a
9、 supplier but no P.(select city from S)except(select city from P)聚集函数 avg min max sum count聚集函数-续 Find the average QTY that is supplied by supplier s1. select avg (QTY) from SP where s#= s1 Find the number of tuples in the supplier relation. select count (*) from S Find the number of suppliers who s
10、upply part. select count (distinct s#) from SP聚集函数-续 Find the number of part for each supplier.select sname, count (distinct p#)from S, SPwhere S.s# = SP.s#group by sname留意: select 短语中出如今聚集函数外面的属性必需求在 group by 列表中聚集函数-续 Find the number of all suppliers who have supplied part more than 600.select s#,
11、 avg (QTY)from SPgroup by s#having avg (QTY) 600聚集函数-续 Note: having 短语 和 where短语的不同处 select d#, avg (SAL)from EMP where age 600空值 元组的某些属性有能够取空值, 记为 null null 表示一个未知的值或者表示一个不存在的值. 任何涉及 null 的算术运算的结果是 null E.g. 5 + null returns null 聚集函数计算中将忽略空值空值-续 is null 谓词用于判别空值. E.g. Find all Employee number whic
12、h appear in the EMP relation with null values for d#.select E#from EMPwhere d# is null 任何与 null 的比较运算结果是 unknown E.g. 5 null or null null or null = null空值-续 Total all part quantityselect sum (QTY)from SP 上述语句忽略空值 QTY 假设没有非空的 QTY,结果是null 除了 count(*) ,一切聚集函数计算都忽略 null values .嵌套子查询 SQL provides a mech
13、anism for the nesting of subqueries. A subquery is a select-from-where expression that is nested within another query. A common use of subqueries is to perform tests for set membership, set comparisons, and set cardinality.举例 Find all employees who have worked in sales department.select distinct Ena
14、mefrom EMPwhere d# in (select d# from DEPT where Dname=sale)集合比较 Find all employees whose salary greater than some managers salary .select Enamefrom EMPwhere sal some (select sal from EMP where E# in ( select mgr from DEPT)集合比较-续 Find the names of all employees whose salary greater than all managers
15、 salary . select Enamefrom EMPwhere sal all(select sal from EMPwhere E# in ( select mgr from DEPT)集合比较-续 Definition of set comparison F some r t r s.t. (F t) F all r t r (F t) Where can be: 集合比较-续056(5 some) = true050) = false505(5 some) = true (since 0 5)(read: 5 some tuple in the relation)(5 some)
16、 = true(5 = some (= some) in However, ( some) not in集合比较-续056(5 all) = false6104) = true546(5 all) = true (since 5 4 and 5 6)(5= 5000)删除 Delete all suppliers who are in Londondelete from Swhere city = London Delete all suppliers who supply part p2.delete from Swhere s# in ( select s# from SP where p
17、#=p2)Note: Here has some problem with constraints that will explained in Chapter 8 Delete the record of all employees with salary below the average .delete from EMPwhere SAL 4000update EMPset SAL = SAL 1.05where SAL 4000 The order is important更多举例 Find all employees who have the lowest salary in eac
18、h department. Select Ename, d#, SAL From EMP Where SAL in (Select min(SAL) From EMP Group By d#) Note: Above statement has error, the correct is: Select Ename, d#, SAL From EMP Where (d#,SAL) in (Select d#,min(SAL) From EMP Group By d#)更多举例-续 Find all part number and its total quantity Select p#, su
19、m(QTY) totqty From SP Group By p#; or equivalently Select p#, (Select sum(QTY) From SP Where SP.p#=P.p#) totqty From P;嵌入 SQL The SQL standard defines embeddings of SQL in a variety of programming languages such as Pascal, PL/I, Fortran, C, and Cobol. A language to which SQL queries are embedded is
20、referred to as a host language, and the SQL structures permitted in the host language comprise embedded SQL.嵌入 SQL-续 The basic form of these languages follows that of the System R embedding of SQL into PL/I. EXEC SQL statement is used to identify embedded SQL request to the preprocessorEXEC SQL Note
21、: this varies by language. E.g. the Java embedding uses # SQL . ; 嵌入 SQL-续 Query single tuple EXEC SQL Select Ename INTO :ename From EMP Where e# = e1 Query set tuples There are dismached problem between host language with sub-language, using middle relation to solve this question. Note: “:ename cal
22、led host variable which need declared by special statement. 嵌入 SQL-续EXEC SQL BEGIN DECLARE SECTION; Char SQLSTATE6; Char P# 6; int Weight;EXEC SQL END DECLARE SECTION; P#=P2;EXEC SQL Select P.weight INTO :weight FROM P WHERE P.P#=:P#;If SQLSTATE=00000Then.Else. ; 嵌入 SQL-续 The statement for SQLSTATE
23、EXEC SQL WHENEVER Conditon Not found no data was found 02000 Sqlerror an error occurred 举例 Specify the query in SQL and declare a cursor for it EXEC SQLdeclare c cursor for select sname, cityfrom S, SP where S.s# = SP.s# and SP.QTY :amountFrom within a host language, find the names and cities of sup
24、pliers supply more than the variable amount quantity part.嵌入 SQL-续 The open statement causes the query to be evaluatedEXEC SQL open c The fetch statement causes the values of one tuple in the query result to be placed on host language variables. EXEC SQL fetch c into :cn, :cc Repeated calls to fetch
25、 get successive tuples in the query result嵌入 SQL-续 A variable called SQLSTATE in the SQL communication area (SQLCA) gets set to 02000 to indicate no more data is available The close statement causes the database system to delete the temporary relation that holds the result of the query.EXEC SQL clos
26、e c Note: above details vary with language. E.g. the Java embedding defines Java iterators to step through result tuples.游标更新nCan update tuples fetched by cursor by declaring that the cursor is for updaten declare c cursor for select * from EMP where city = Parise for updatenTo update tuple at the c
27、urrent location of cursorn update EMP set SAL = SAL + 100 where current of c动态 SQL Allows programs to construct and submit SQL queries at run time. The dynamic SQL program contains a ?, which is a place holder for a value that is provided when the SQL program is executed.动态 SQL-续 Example of the use
28、of dynamic SQL from within a C program.char * sqlprog = “update EMP set SAL = SAL * 1.05 where d# = ?EXEC SQL prepare dynprog from :sqlprog; char account 10 = “A-101;EXEC SQL execute dynprog using :account;ODBC Open DataBase Connectivity(ODBC) standard standard for application program to communicate
29、 with a database server. application program interface (API) to open a connection with a database, send queries and updates, get back results. Applications such as GUI, spreadsheets, etc. can use ODBCODBC - 续 Each database system supporting ODBC provides a driver library that must be linked with the
30、 client program. When client program makes an ODBC API call, the code in the library communicates with the server to carry out the requested action, and fetch results. ODBC program first allocates an SQL environment, then a database connection handle.ODBC - 续 Opens database connection using SQLConne
31、ct(). Parameters for SQLConnect: connection handle, the server to which to connect the user identifier, password Must also specify types of arguments: SQL_NTS denotes previous argument is a null-terminated string.ODBC 编程int ODBCexample() RETCODE error; HENV env; /* environment */ HDBC conn; /* database connection */ SQLAllocEnv(&env
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 广东省韶关市2019-2020学年七年级上学期期末历史试题(含答案)
- 2027年汽车物流合同二篇
- 2027年转租房屋租房合同二篇
- 合规转利润:降本增效全指南(2026)《GBT 36418-2018絮用纤维制品有机挥发性物质的测定》
- 合规转利润:降本增效全指南(2026)《GBT 36112-2018政务服务中心服务现场管理规范》
- 合规转利润:降本增效全指南(2026)《GBT 35998-2018甘蔗和蔗渣的蔗糖分、锤度及纤维分测定 湿式分解法》
- 塑料浇铸工岗前诚信品质考核试卷含答案
- 《中华人民共和国行政强制法》法律知识竞赛试题及参考答案
- 水产品冻结工操作规程强化考核试卷含答案
- 钽铌化合物制取工岗前技能评估考核试卷含答案
- 2026盐城市国资委直属事业单位公开选调工作人员考试参考题库及答案详解
- 2026 年秋季开学大学军训网络文明行为教育课件
- 2026年外研版五年级英语上册单词表衡水体描红英语字帖(三年级起点)
- 2026中国智能仓储物流机器人系统集成市场发展白皮书
- 放射科肺部CT影像评估培训指南
- 人教版(2024)七年级上册生物全册教学设计
- 机修钳工(高级)证考试题及答案
- 林下仿野生黄精种植技师考试试卷及答案
- 24J113-1 内隔墙-轻质条板(一)
- 汽修事故隐患内部报告奖励制度
- 《老年人活动策划与组织》智慧健康养老专业全套教学课件
评论
0/150
提交评论