Sie sind auf Seite 1von 32

CO1019: Databases and

Web Applications
SQL Part 3:
Subqueries and Multiple Tables

Dr. Karim Mualla

CO1019 Databases and Web Applications 1


Previously on CO1019:
 CREATE tables, INSERT data into table and SELECT
data out of table
 Use Aggregate functions
 UPDATE data and DELETE data from table
◦ ALL ON ONE TABLE ONLY!
 Create a Union between two identical queries of
different tables

CO1019: Databases and Web


Applications 2
StaffNo Fname Lname Position Salary
222 Head Honcho CEO 35000
322 Mark Jones Manager 20000
261 Julie Walters Director 40000
260 Julie Walters Tax Shelter 20000
555 Dogollan Body Cleaner 500
444 Trinity Wells Porter 200
401 Taffy Truman Manager 30000
322 Gareth Whirlwind Manager 32500
Using Subqueries - Nested SELECTs
 If we know that a SELECT statement will produce a single value or
row we can use this value directly in a simple predicate.
 This subquery must appear in brackets ();
ORDER BY can't appear in a subquery;
most subqueries can't have more than 1 table in SELECT list
 Can appear after a relational operator, function or set operator in
WHERE, SELECT & HAVING clauses
 Example: find all members of staff who earn more than the
managers:
SELECT * FROM Staff WHERE Salary > (SELECT
Salary FROM Staff WHERE Position
='Manager');
Would this work if we introduce multiple managers?

CO1019 Database and Web Applications 4


Subqueries That Give a List of Values
 If the SELECT statement is expected to produce a list
of values, we can use the IN, ANY, ALL or EXISTS
keywords to operate on the list.

 Example: find those members of staff who are not


managers but earn more than any managers:

SELECT * FROM Staff WHERE Position <>


'Manager' AND Salary > ANY (SELECT Salary
FROM Staff WHERE Position = 'Manager');

ANY: Predicate is true if it matches ANY value in the list


e.g. statement is true if staff is not a manager and has a higher
salary than any manager.

CO1019 Database and Web Applications 5


Subqueries That Give a List of Values
 SELECT * FROM Staff WHERE Position <>
'Manager' AND Salary > ALL (SELECT
Salary FROM Staff WHERE Position
='Manager');

ALL: Predicate is true if it matches ALL value in the list


e.g. statement is true if staff is not a manager and has a
higher salary than ALL the managers.

 SELECT * FROM Staff WHERE position IN


('Manager', 'Supervisor');

IN: Predicate is true if the test element is in the list; (i.e.


if position is IN the set of values we supply - Manager
or Supervisor)

CO1019 Database and Web Applications 6


Subqueries That Give a List of Values
The SQL EXISTS Operator

 The EXISTS operator is used to test for the existence


of any record in a subquery.

 The EXISTS operator returns true if the subquery


returns one or more records.

SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE conditio
n);

CO1019 Database and Web Applications 7


Subqueries That Give a List of Values
 The following SQL statement returns TRUE and lists the suppliers with
a product price less than 20:

SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Suppli
erId = Suppliers.supplierId AND Price < 20);

 The following SQL statement returns TRUE and lists the suppliers with
a product price equal to 22:

SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Suppli
erId = Suppliers.supplierId AND Price = 22);

CO1019 Database and Web Applications 8


Querying Multiple Tables
•How do we list all the properties that a given client has viewed?
•Could start with an example - e.g. client CR56 ...
PropertyForRent
PropertyNo Street City Postcode Type Rooms Rent OwnerNo StaffNo BranchNo
PA14 16 Holhead Aberdeen AB7 5SU House 6 650 CO46 SA9 B007
PG16 5 Novar Dr Glasgow G12 9AX Flat 4 450 CO93 SG14 B003
PG21 18 Dale Rd Glasgow G12 House 5 600 CO87 SG37 B003
PG36 2 Manor Rd Glasgow G32 4QX Flat 3 375 CO93 SG37 B003
PG4 6 Lawrence St Glasgow G11 9QX Flat 3 350 CO40 B003

PL94 6 Argyll St London NW2 Flat 4 400 CO87 SL41 B005

Client Viewing
ClientNo PropertyNo ViewDate Comment
ClientNo Fname Lname TelNo PrefType MaxRent CR56 PA14 24-May-01 too small
CR56 Aline Stewart 0141-848-1825 Flat 350 CR56 PG36 28-Apr-01
CR62 Mary Tregear 01224-196720 Flat 600
CR74 Mike Ritchie 01475-392178 House 750
CR56 PG4 26-May-01
CR76 John Kay 0207-774-5632 Flat 425

CR62 PA14 14-May-01 no dining room


CR76 PG4 20-Apr-01 too remote

CO1019 Database and Web Applications 9


Property Query - First Attempt
 First attempt: List the property numbers viewed by client
number 'CR56':
SELECT PropertyNo
FROM Viewing
WHERE ClientNo = 'CR56';
 But we'd like to see the client name & property details
 So we'll need to access Client and PropertyForRent for
names etc...
 To obtain info from >1 table: subqueries or joins; for result
table to contain columns from >1 table: join.
 Recall subqueries: SELECT * FROM Staff WHERE branchNo =
(SELECT branchNo FROM Branch WHERE street =
'163 Main St');

CO1019 Database and Web Applications 10


Property Query - Second Version
SELECT DISTINCT Viewing.PropertyNo, Street, City,
ViewDate
FROM Viewing, PropertyForRent
WHERE ClientNo = 'CR56'
AND Viewing.PropertyNo = PropertyForRent.PropertyNo; (matching
cols)

 We now have two table names in the FROM clause


 Note use of “Table.ColumnName" to avoid ambiguity in
column names (i.e. both Viewing and PropertyForRent
have a PropertyNo column)

CO1019 Database and Web Applications 11


Property Query - Third Version
SELECT DISTINCT Fname, Lname, Street, City, ViewDate
FROM Viewing, PropertyForRent, Client
WHERE Viewing.ClientNo = 'CR56'
AND Viewing.PropertyNo = PropertyForRent.PropertyNo
AND Viewing.ClientNo = Client.ClientNo;

 The two “AND" clauses are called join criteria

CO1019 Database and Web Applications 12


Property Query - Fourth Version
 Users shouldn't have to know about internal keys...
SELECT DISTINCT Fname, Lname, Street, City, ViewDate
FROM Viewing, PropertyForRent, Client
WHERE Fname = 'Aline' AND Lname = 'Stewart'
AND Viewing.PropertyNo = PropertyForRent.PropertyNo;
AND Viewing.ClientNo = Client.ClientNo;

CO1019 Database and Web Applications 13


Using Table Aliases
 Table aliases can help reduce amount of typing
 The following is identical to the previous query:
SELECT C.Fname, C.Lname, P.Street, P.City,
V.ViewDate
FROM Viewing V, PropertyForRent P, Client C
WHERE C.Fname = 'Aline' AND C.Lname = 'Stewart'
AND V.PropertyNo = P.PropertyNo
AND V.ClientNo = C.ClientNo;

 Table aliases help reduce the risk of typing


mistakes

CO1019 Database and Web


Applications 14
JOIN
 An SQL JOIN clause is used to combine rows
from two or more tables, based on a common
field between them.
 The most common type of join is: SQL
INNER JOIN (simple join).
 An SQL INNER JOIN returns all rows from
multiple tables where the join condition is met.

CO1019 Database and Web


Applications 15
Types of JOINs:
Different SQL JOINs:

•INNER JOIN: Returns all rows when there is at least one


match in BOTH tables

•LEFT JOIN: Return all rows from the left table, and the
matched rows from the right table

•RIGHT JOIN: Return all rows from the right table, and the
matched rows from the left table

•FULL JOIN: Return all rows when there is a match in ONE of


the tables
INNER JOIN: Example
Below is only a selection from the "Orders" table:

Below is only a selection from the "Customers" table:

CO1019 Database and Web


Applications 18
INNER JOIN: Example
LEFT JOIN:
LEFT JOIN: Example
LEFT JOIN: Example
Return all customers, and any orders they might have

The LEFT JOIN keyword returns all the rows from the left
table (Customers), even if there are no matches in the right
table (Orders).

Example is available at:


http://www.w3schools.com/sql/sql_join_left.asp
RIGHT JOIN:
FULL JOIN:
NATURAL JOIN
 Different types of join
◦ The SQL NATURAL JOIN is structured in such a way that,
columns with the same name of associated tables will
appear once only.

◦ Natural Join : Guidelines

- The associated tables have one or more pairs of identically named


columns.
- The columns must be the same data type.
- Don’t use ON clause in a natural join.

 Relationships
◦ 1-* relationships
◦ 1-1 relationships
◦ *-* relationships
CO1019 Databases and Web Applications 25
NATURAL JOIN

CO1019 Databases and Web Applications 26


NATURAL JOIN

CO1019 Databases and Web Applications 27


NATURAL JOIN

CO1019 Databases and Web Applications 28


NATURAL JOIN vs INNER JOIN

CO1019 Databases and Web Applications 29


NATURAL JOIN

CO1019 Databases and Web Applications 30


NATURAL JOIN

CO1019 Databases and Web Applications 31


Other Types of Joins:
 Theta Joins
 Cross Joins
 Explicit Joins
 Implicit Joins
 Self-Joins
 Semi join

 Further Reading: http://www.w3schools.com/sql/sql_join.asp

CO1019 Database and Web Applications 32

Das könnte Ihnen auch gefallen