Structured Query Language (II) (結構化查詢語言)

Slides:



Advertisements
Similar presentations
© Abdou Illia MIS Spring 2014
Advertisements

Chapter 4 Joining Multiple Tables
A Guide to SQL, Seventh Edition. Objectives Use joins to retrieve data from more than one table Use the IN and EXISTS operators to query multiple tables.
Relational Algebra, Join and QBE Yong Choi School of Business CSUB, Bakersfield.
5 Copyright © 2004, Oracle. All rights reserved. Displaying Data from Multiple Tables.
Structured Query Language Part I Chapter Three CIS 218.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
Displaying Data from Multiple Tables. Obtaining Data from Multiple Tables Sometimes you need to use data from more than one table. In the example, the.
Objectives After completing this lesson, you should be able to do the following: Write SELECT statements to access data from more than one table using.
Structured Query Language Introduction to SQL What is SQL? – –When a user wants to get some information from a database file, he can issue a query.1.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
SQL 資料庫查詢語言 取材自 EIS, 3 rd edition By Dunn et al..
HAP 709 – Healthcare Databases SQL Data Manipulation Language (DML) Updated Fall, 2009.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
Chapter 9 Joining Data from Multiple Tables
Sections 3 – Joins & Hierarchical Queries
Copyright © 2004, Oracle. All rights reserved. Lecture 6 Displaying Data from Multiple Tables ORACLE.
Oracle Database Administration Lecture 2 SQL language.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
Structured Query Language ( 結構化查詢語言 ) Database Programming CREATE TABLE … ALTER TABLE… ADD/DROP/MODIFY (…) DESC … DROP TABLE … RENAME … TO … INSERT INTO.
Using Special Operators (LIKE and IN)
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
Chapter 4Introduction to Oracle9i: SQL1 Chapter 4 Joining Multiple Tables.
Unit 4 Queries and Joins. Key Concepts Using the SELECT statement Statement clauses Subqueries Multiple table statements Using table pseudonyms Inner.
Join, Subqueries and set operators. Obtaining Data from Multiple Tables EMPLOYEES DEPARTMENTS … …
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
5 Copyright © 2004, Oracle. All rights reserved. Displaying Data from Multiple Tables.
5 Copyright © 2004, Oracle. All rights reserved. Displaying Data from Multiple Tables.
Intermediate SQL: Aggregated Data, Joins and Set Operators.
Structured Query Language ( 結構化查詢語言 ) Lesson Review What is S Q L?L? When a user wants to get some information from a database file, he can issue a _______.
Database Programming Sections 4 – Joins. Marge Hohly2 Overview  Oracle Proprietary Joins (8i and prior): Cartesian Product Equijoin Non-equijoin Outer.
Structured Query Language Introduction. Basic Select SELECT lname, fname, phone FROM employees; Employees Table LNAMEFNAMEPHONE JonesMark SmithSara
Database Programming Section 15 – Oracle Proprietary Join Syntax and Review 1.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
Hassan Tariq MULTIPLE TABLES: SQL provides a convenient operation to retrieve information from multiple tables.SQL provides a convenient operation to.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 The Relational Algebra and Relational Calculus.
Database Programming Sections 3 – Oracle Joins. Marge Hohly2 Obtaining Data from Multiple Tables: Using Joins.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
SQL BY MR.PRASAD SAWANT INDIA Introduction to SQL What is SQL? –When a user wants to get some information from a database file, he can issue a query.1.
5-1 Copyright © 2004, Oracle. All rights reserved. DISPLAYING DATA FROM MULTIPLE TABLES OUTER JOIN.
Select Complex Queries Database Management Fundamentals LESSON 3.1b.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
CS3220 Web and Internet Programming More SQL
Displaying Data from Multiple Tables
Oracle Join Syntax.
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Structured Query Language
Using the Set Operators
Displaying Data from Multiple Tables Using Joins
SQL.
Sections 4– Review of Joins, Group functions, COUNT, DISTINCT, NVL
Oracle Join Syntax.
Structured Query Language
CS4222 Principles of Database System
Contents Preface I Introduction Lesson Objectives I-2
Query Functions.
Chapter 8 Advanced SQL.
Oracle Join Syntax.
Joins and other advanced Queries
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Presentation transcript:

Structured Query Language (II) (結構化查詢語言) SQL Structured Query Language (II) (結構化查詢語言) 2018/12/1

SQL query – Grouping SELECT ...... FROM ...... WHERE condition GROUP BY groupexpr [HAVING requirement] Group functions: COUNT( ), SUM( ), AVG( ), MAX( ), MIN( ) – groupexpr specifies the related rows to be grouped as one entry. Usually it is a column. – WHERE condition specifies the condition of individual rows before the rows are group. HAVING requirement specifies the condition involving the whole group. 2018/12/1

Example field type width contents id numeric 4 student id number Table: stud field type width contents id numeric 4 student id number name character 10 name dob date 8 date of birth sex character 1 sex: M / F class character 2 class hcode character 1 house code: R, Y, B, G dcode character 3 district code remission logical 1 fee remission (學費減免) mtest numeric 2 Math test score 2018/12/1

1A 1A 1B 1C 1B 1C Group By Class COUNT( ) COUNT( ) COUNT( ) e.g.1 List the number of students of each class. Group By Class Stud class 1A 1B 1C 1A 1A 1B 1C COUNT( ) COUNT( ) 1B COUNT( ) 1C 2018/12/1

Grouping SELECT class, COUNT(*) FROM stud GROUP BY class eg. 1 List the number of students of each class. SELECT class, COUNT(*) FROM stud GROUP BY class Result 2018/12/1

Grouping SELECT class, Round(AVG(mtest),2) FROM stud GROUP BY class e.g. 2 List the average Math test score of each class. SELECT class, Round(AVG(mtest),2) FROM stud GROUP BY class Result 2018/12/1

Grouping SELECT dcode, COUNT(*) FROM stud WHERE sex=‘F’ GROUP BY dcode e.g. 3 List the number of girls of each district. SELECT dcode, COUNT(*) FROM stud WHERE sex=‘F’ GROUP BY dcode Result 2018/12/1

Grouping SELECT MAX(mtest), MIN(mtest), dcode FROM stud e.g. 4 List the max. and min. test score of Form 1 students of each district. SELECT MAX(mtest), MIN(mtest), dcode FROM stud WHERE class LIKE ‘1_’ GROUP BY dcode Result 2018/12/1

Grouping SELECT AVG(mtest), class FROM stud WHERE sex=‘M’ e.g. 5 List the average Math test score of the boys in each class. The list should not contain class with less than 3 boys. SELECT AVG(mtest), class FROM stud WHERE sex=‘M’ GROUP BY class HAVING COUNT(*) >= 3 Result 2018/12/1

Grouping 2018/12/1

Multiple Tables – Join by Columns: SQL provides a convenient operation to retrieve information from multiple tables. This operation is called . Join (接合) The join operation will combine the tables into one large table by . columns (欄) An Inner Join is a join operation that joins two tables by their . common column (共通欄) It combines records from two tables only if the values of the joined fields meet a specified condition. The join operation is also called . Equi-Join 2018/12/1

1. Inner Join (內接合) – Syntax SELECT a.comcol, a.col1, b.col2, expr1, expr2 ; FROM table1 a, table2 b ; WHERE a.comcol = b.comcol and filterCondition 2018/12/1

Table : d_play_list_items Table : d_track_listings 1. Equi-Join / Inner Join Table : d_play_list_items Table : d_track_listings 2018/12/1

Example: Music Instrument learnt by students Table: stud field type width contents id numeric 4 student id number name character 10 name dob date 8 date of birth sex character 1 sex: M / F class character 2 class hcode character 1 house code: R, Y, B, G dcode character 3 district code remission logical 1 fee remission (學費減免) mtest numeric 2 Math test score Table: music field type width contents id numeric 4 student id number type character 10 type of the music instrument 2018/12/1 Join by The common field: id

they learn. (Inner Join) eg.1 Make a list of students and the instruments they learn. (Inner Join) Student 9801 id name class Music id 9801 type Same id Join 9801 Product id name class type 2018/12/1

they learn. (Inner Join) eg.1 Make a list of students and the instruments they learn. (Inner Join) SELECT s.class, s.name, s.id, m.type FROM stud s, music m WHERE s.id=m.id ORDER BY class, name Result 2018/12/1

(2) Condition: m.type="Piano" (3) GROUP BY class eg.2 Find the number of students learning piano in each class. Three Parts : (1) Inner Join. (2) Condition: m.type="Piano" (3) GROUP BY class 2018/12/1

in each class. eg.2 Find the number of students learning piano Join Music Student Join Product Condition m.type= "Piano" Group By class 2018/12/1

SELECT s.class, COUNT(*) FROM stud s, music m eg.2 Find the number of students learning piano in each class. SELECT s.class, COUNT(*) FROM stud s, music m WHERE s.id=m.id AND m.type=‘Piano’ GROUP BY class ORDER BY class Result 2018/12/1

Other Examples of Inner Join In a DBMS of a Musical Instrumental Co. , 3 tables are used: Salorder m m Client 1 1 Salstaff 2018/12/1

SELECT O.order_no, C.client, C.name FROM salOrder O, Client C e.g1 Display the names of the contact person and client, corresponding to the same order. (Two Tables) SELECT O.order_no, C.client, C.name FROM salOrder O, Client C WHERE O.client_id =C.client_id Result 2018/12/1

SELECT O.order_no, S.name as salesperson, O.order_date e.g.2 Display the sales orders made between May and June , with the corresponding salespersons in the same cursor (list by date). SELECT O.order_no, S.name as salesperson, O.order_date FROM salOrder O, salStaff S WHERE O.staff_id=S.staff_id and order_date between '1-5月-2006' and '30-6月-2006' ORDER BY 3 Result 2018/12/1

e.g.3 Display the names of the contact person , client and the salesperson corresponding to the same sales order. (3 Tables) SELECT O.order_no, C.client, C.name as contact, S.name as salesperson FROM salOrder O, client C, salStaff S WHERE O.staff_id=S.staff_id and O.client_id=C.client_id From salOrder From client From client From salStaff Result 2018/12/1

2. Nonequi-Join SELECT d_packages.code, d_events.cost FROM d_packages, d_events WHERE d_events.cost BETWEEN d_packages.low_range AND d_packages.high_range 2018/12/1

3. Outer Join (外接合) An Outer Join is a join operation that selects all the rows from the first table including those match and those do not match the rows in the second table. Those not matching join condition will be a (-) value. null 2018/12/1

3. Left Outer Join – Syntax SELECT a.comcol, a.col1, b.col2, expr1, expr2 ; FROM table1 a LEFT OUTER JOIN table2 b ; ON a.comcol = b.comcol WHERE filterCondition ORDER BY … SELECT a.comcol, a.col1, b.col2, expr1, expr2 ; FROM table1 a, table2 b ; WHERE a.comcol = b.comcol (+) and filterCondition ORDER BY … (+) sign indicates the table has missing data. 2018/12/1

Inner Join Outer Join No Match eg. Make a checking list of students and the instruments they learn. The list should also contain the students without an instrument. (Outer Join) Inner Join Outer Join No Match 2018/12/1

eg. Make a checking list of students and the. instruments they learn eg. Make a checking list of students and the instruments they learn. The list should also contain the students without an instrument. (Outer Join) SELECT s.class, s.name, s.id, m.type FROM stud s LEFT OUTER JOIN music m ON s.id=m.id ORDER BY 1, 2 FROM stud s, music m where s.id=m.id(+) order by 1,2 Result Outer Join empty 2018/12/1

Select e.employee_id, e.last_name, d.department_name 3. Outer Join Null value Select e.employee_id, e.last_name, d.department_name From employees e, departments d Where e.department_id=d.department_id(+) 2018/12/1

3. Outer Join (Right Outer Join) Select e.last_name, e.department_id, d.department_name From employees e, departments d Where e.department_id (+) =d.department_id The right outer join would return all department IDs and department names even if no employees were assigned to them. 2018/12/1

3. Outer Join (Full Outer Join) The results set of a full outer join includes all rows in both tables even if there is no match in the other table. Remember, in this form of an outer join, it was not possible to put a (+) on both sides of the WHERE clause. 2018/12/1

4. Cartesian Product / Cross Join 1. Select * from stud 2. Select * from music 3. Select * from stud, music 4. Select * from stud cross join music How many records before and after the join? 2018/12/1

Select worker.last_name ||' works for '|| manager.last_name 5. SELF JOIN Table : Employees Select worker.last_name ||' works for '|| manager.last_name From employees worker, employees manager Where worker.manager_id = manager.employee_id 2018/12/1

6. NATURAL JOIN A natural join is based on all columns in the two tables that have the same name and selects rows from the two tables that have equal values in all matched columns. It is possible to join the tables without having to explicitly specify the columns in the corresponding table. However, the names and data types in both columns must be the same. Table : d_track_listings Table : d_play_list_items SELECT event_id, song_id, cd_number FROM d_play_list_items NATURAL JOIN d_track_listings WHERE event_id = 105 2018/12/1

JOIN (USING Clause) 2018/12/1

JOIN (ON Clause) 2018/12/1

There are two types of subqueries: -Single-row subqueries that use single-row operators (>, =, >=, < <>, <=) and return only one row from the inner query e.g. SELECT name from stud where mtest <= (select avg(mtest) from stud) Multiple-row subqueries that use multiple-row operators (IN, ANY, ALL) and return more than one row from the inner query 2018/12/1

Subqueries - IN IN (= ANY) NOT IN (<> ALL) SELECT title, year FROM d_cds WHERE year IN (SELECT year WHERE cd_number < 94) IN (= ANY) NOT IN (<> ALL) 2018/12/1

Subqueries - ANY SELECT title, producer, year FROM d_cds WHERE year = ANY (SELECT year WHERE producer = 'The Music Man') 2018/12/1

Subqueries - ALL SELECT title, producer,year FROM d_cds WHERE year > ALL (SELECT year WHERE producer = 'The Music Man') 2018/12/1

Tutorial Exercise Time 2018/12/1

The End 2018/12/1

The union (數據庫聯合) of A and B (AB) Lesson Review Two Tables with same structure: Table A and Table B What is Union in Multiple Tables? The union (數據庫聯合) of A and B (AB) A table containing all the rows from A and B. A B 2018/12/1

Real Case: Bridge Club & Chess Club Consider the members of the Bridge Club and the Chess Club. The two database files have the same structure: Union List members of either clubs order by class, name 2018/12/1

The intersection (數據庫相交) of A and B (AB) Lesson Review Two Tables with same structure: Table A and Table B What is Intersection in Multiple Tables? The intersection (數據庫相交) of A and B (AB) A table containing only rows that appear in both A and B. A B 2018/12/1

Real Case: Bridge Club & Chess Club Consider the members of the Bridge Club and the Chess Club. The two database files have the same structure: Intersection Members of both clubs 2018/12/1

The difference (數據庫差分) of A and B (A–B) Lesson Review Two Tables with same structure: Table A and Table B What is Difference in Multiple Tables? The difference (數據庫差分) of A and B (A–B) A table containing rows that appear in A but not in B. A B 2018/12/1

Real Case: Bridge Club & Chess Club Consider the members of the Bridge Club and the Chess Club. The two database files have the same structure: Difference Members of Bridge Club but Not Chess Club 2018/12/1

Lesson Review 1. Union Syntax of SQL SELECT ...... FROM ...... WHERE ...... ; UNION ; SELECT ...... FROM ...... WHERE ...... 2018/12/1

Lesson Review 2. Intersection Syntax of SQL SELECT ...... FROM table1 ; WHERE col IN ( SELECT col FROM table2 ) Note: col stands for one of the common column in the two tables 2018/12/1

Lesson Review 3. Difference Syntax of SQL SELECT ...... FROM table1 ; WHERE col NOT IN ( SELECT col FROM table2 ) Note: col stands for one of the common column in the two tables 2018/12/1

This Lesson eg. 9 List the students who have not yet chosen an instrument. (No match) Student 9801 id name class Music id type No match 2018/12/1

WHERE id NOT IN ( SELECT id FROM music ) ; eg. 9 List the students who have not yet chosen an instrument. No match (Difference) SELECT class, name, id FROM student ; WHERE id NOT IN ( SELECT id FROM music ) ; ORDER BY class, name Result 2018/12/1