Академический Документы
Профессиональный Документы
Культура Документы
Chapter 4
Queries
Jerry Post
Copyright 2007
1
D Objectives
A
Why do you need a query language?
T What are the main tasks of a query language?
S SQL?
How do you compute subtotals?
E How do you use multiple tables in a query?
2
D Why do we Need Queries
A
Natural languages (English) are too vague
T With complex questions, it can be hard to verify that the
question was interpreted correctly, and that the answer we
A received is truly correct.
Consider the question: Who are our best customers?
B We need a query system with more structure
We need a standardized system so users and
A developers can learn one method that works on any
(most) systems.
S Query By Example (QBE)
SQL
E
3
D Four Questions to Create a Query
A
What output do you want to see?
T What do you already know (or what constraints are
A given)?
What tables are involved?
B How are the tables joined together?
A
S
E
4
D Joining Tables
A Sales
SaleID
SaleDate
Customer
CustomerID
LastName
T
CustomerID FirstName
Phone
A
SaleID SaleDate CustomerID CustomerID LastName FirstName Phone
1 5/1 1 1 Jones Mary 111-2222
2 5/1 2 2 Smith Marta 222-3333
B 3
4
5/2
5/2
4
1
3
4
Jackson
Smith
Miguel
Mark
444-2222
555-5662
S 1
2
5/1
5/1
1
2
1
2
Jones
Smith
Mary
Marta
111-2222
222-3333
E
3 5/2 4 4 Smith Mark 555-5662
4 5/2 1 1 Jones Mary 111-2222
5
D Sales
Customer Cross Join (Bad)
SaleID
A SaleDate
CustomerID
CustomerID
LastName
FirstName
T
Phone
A
1 5/1 1
2 5/1 2 2 Smith Marta 222-3333
B 4 5/2
SaleID
1
SaleDate CustomerID
4
CustomerID
Smith
LastName
Mark
FirstName
555-5662
Phone
A 1
1
5/1
5/1
1
1
1
2
Jones
Smith
Mary
Marta
111-2222
222-3333
S 1
1
5/1
5/1
1
1
3
4
Jackson
Smith
Miguel
Mark
444-2222
555-5662
2 5/1 2 1 Jones Mary 111-2222
E 2
2
5/1
5/1
2
2
2
3
Smith
Jackson
Marta
Miguel
222-3333
444-2222
2 5/1 2 4 Smith Mark 555-5662
8 more rows 6
D Tables Animal
A
AnimalOrder Animal AnimalID
OrderItem Name SaleAnimal
OrderID * * *
OrderID Category
OrderDate * SaleID
AnimalID Breed
* ReceiveDate AnimalID
Cost Breed * DateBorn
T
SupplierID * SalePrice
Gender
ShippingCost Category
Registered
EmployeeID * Breed
Color
Employee
ListPrice
Supplier Customer
A
EmployeeID Photo
SupplierID LastName CustomerID
Name City FirstName Sale Phone
ContactName Phone FirstName
CityID SaleID
Phone Address LastName
ZipCode SaleDate
B
Address ZipCode * Address
City EmployeeID
ZipCode * CityID ZipCode
State CustomerID * *
CityID TaxPayerID CityID
AreaCode SalesTax
* DateHired Category
Population1990
DateReleased
A
Population1980 Category
Country Registration
SaleItem
Latitude
*
Longitude Merchandise SaleID
OrderItem
ItemID
* ItemID
S
Merchandise PONumber * Quantity
* Description
Order ItemID SalePrice
QuantityOnHand
Quantity
PONumber ListPrice
Cost
OrderDate Category
ReceiveDate *
E *
SupplierID
EmployeeID
ShippingCost *
7
D Organization
A
Single table
T Constraints
A Computations
Groups/Subtotals
B Multiple Tables
A
S
E
8
D Sample Questions
A Which cats were born after June 1?
List the animals by category and
What is the total value of order
number 22?
T
breed. How many animals were sold in
List the categories of animals that each category?
are in the Animal list. How many animals were sold in
A Which dogs have a list price greater each category with total sales more
than $250? than 10?
Which cats have black in their How many animals born after June
B
color? 1 were sold in each category with
List cats excluding those that are total sales more than 10?
registered or have red in their color. List the CustomerID of everyone
who bought something between
A List all dogs who are male and
registered or who were born before
01-June-2007 and have white in
April 1, 2007 and May 31, 2007.
List the names of everyone who
bought something between April 1,
S
their color.
What is the extended value (price * 2007 and May 31, 2007.
quantity) for sale items on sale 24? List the name and phone number of
anyone who bought a registered
E
What is the average sale price of
animals? white cat between two given dates
9
D Query04_Fig06
T Name
Category
Breed
A DateBorn
Gender What animals were born after August 1?
B Field
Table
AnimalID Name
Animal
Category DateBorn
Animal Animal Animal
A Sort
Criteria >01-Aug-2007
S Or
E
FROM Animal
WHERE DateBorn > 01-Aug-2007;
10
D Basic SQL SELECT
A
T SELECT columns
FROM tables
What do you want to see?
What tables are involved?
A JOIN conditions How are the tables joined?
A
S
E
11
D ORDER BY
A SELECT
FROM
columns
tables
JOIN join columns
T WHERE
ORDER BY
conditions
columns (ASC DESC)
12
D DISTINCT
A SELECT Category
FROM Animal;
SELECT DISTINCT Category
FROM Animal;
T Category
Fish
Category
Bird
A
Dog Cat
Fish Dog
Cat Fish
B Cat
Dog
Fish
Mammal
Reptile
A
Spider
Dog
Dog
S
Dog
Fish
Cat
E Dog
...
13
D
Query04_Fig10
Constraints: And
A Animal
AnimalID
T Name
Category
Breed
Which dogs have a list price
greater than $250?.
A DateBorn
Gender
B
Field AnimalID Name Category ListPrice
Table Animal Animal Animal Animal
Sort
A Criteria
Or
Dog >250
E
WHERE Category-Dog AND ListPrice>250;
14
D
Query04_Fig11
Pattern Matching
A Animal
AnimalID
T Name
Category
Breed
Which cats have black in their color?
A DateBorn
Gender
B
Field AnimalID Name Category Color
Table Animal Animal Animal Animal
Sort
A Criteria
Or
Cat LIKE %Black%
E FROM Animal
WHERE Category=Cat AND Color LIKE %Black%;
15
D Boolean Algebra a=3
B T
F
F
T
F
F
T
T
(a > 4) Or (b < 0)
F T
A F F F F T
S NOT (b < 0)
T
E F
16
D Boolean Algebra
A The result is affected by the order
of the operations. a=3
T Parentheses indicate that an
operation should be performed first.
b = -1
17
D
Query04_Fig15
T Name
Category
Breed
Customer: "I want to look at a cat, but I
dont want any cats that are registered
or that have red in their color."
A DateBorn
Gender
B
Field AnimalID Category Registered Color
Table Animal Animal Animal Animal
Sort
A Criteria
Or
Cat Is Null Not Like %Red%
E
WHERE (Category=Cat) AND
NOT ((Registered is NOT NULL)
OR (Color LIKE %Red%)).
18
D DeMorgans Law
A Negation of clauses
Not (A And B) becomes
T Not A Or Not B
Not (A Or B) becomes Registered=ASCF
Not A And Not B Color=Black
A NOT ((Registered is NOT NULL) OR (Color LIKE %Red%))
B T
not
or
T
F
A F
(Registered is NULL) AND NOT (Color LIKE %Red%)
S F
and
not
T
F
E F
19
D
Query04_Fig16
Conditions: And, Or
A Animal
AnimalID
Name
T
List all dogs who are male and registered or who were
Category born before 6/1/2007 and have white in their color.
Breed
DateBorn
A Field
Gender
B Table
Sort
Animal Animal Animal Animal Animal Animal
A
Criteria Dog Male Is Not Null
Or Dog < 01-Jun-2004 Like %White%
S
SELECT AnimalID, Category, Gender, Registered, DateBorn, Color
FROM Animal
WHERE (( Category=Dog) AND
( ( (Gender=Male) AND (Registered Is Not Null) ) OR
20
D Useful Where Conditions
A Comparisons Examples
T Operators <, =, >, <>, >= BETWEEN, LIKE, IN
Numbers AccountBalance > 200
A Text
Simple Name > Jones
B Pattern match one
Pattern match any
License LIKE A_ _82_
Name LIKE J%
A Dates SaleDate BETWEEN 15-Aug-2007
AND 31-Aug-2007
S Missing Data City IS NULL
E Negation
Sets
Name IS NOT NULL
Category IN (Cat, Dog, Hamster)
21
D
Query04_Fig20
Simple Computations
A SaleItem(SaleID, ItemID, SalePrice, Quantity)
T Select SaleID, ItemID, SalePrice, Quantity,
SalePrice*Quantity As Extended
A From SaleItem;
SaleID ItemID Price Quantity Extended
B 24
24
25
26
2.70
5.40 2
3 8.10
10.80
A 24 27 31.50 1 31.50
S
E Basic computations (+ - * /) can be performed on numeric data.
The new display column should be given a meaningful name.
28
D
Query04_Fig21
Computations: Aggregation--Avg
A What is the average sale price of all animals?
T SaleAnimal
SaleID
Sum
Avg
A AnimalID
SalePrice
Min
Max
Count
B Field
Table
SalePrice
SaleAnimal
StDev or
StdDev
Var
A Total
Sort
Avg
S Criteria
Or
29
D
Query04_Fig22
A
Cost
B Table
Total
OrderItem OrderItem
OrderTotal
A
Sort
1798.28
Criteria =22
Or
30
D Task Access
SQL Differences
SQL Server Oracle
A Strings
Concatenation
Length
FName & &
LName
Len(LName)
FName + + LName
Length(LName)
Upper(LName)
FName || || LName
LENGTH(LName)
UPPER(LName)
T Upper case
Lower case
Partial string
UCase(LName)
LCase(LName)
MID(LName,2,3)
Lower(LName)
Substring(LName,2,3)
LOWER(LName)
SUBSTR(LName,2,3)
A Dates
Today
Month
Date( ), Time( ), Now(
)
Month(myDate)
GetDate()
DateName(month,
myDate)
SYSDATE
TRUNC(myDate, mm)
TRUNC (myDate, dd)
B
Day Day(myDate) DatePart(day, myDate) TRUNC (myDate, yyyy)
Year Year(myDate) DatePart(year, myDate) ADD_MONTHS
Date DateAdd DateAdd MONTHS_BETWEEN
arithmetic DateDiff DateDiff LAST_DAY
S
Numbers Cos, Sin, Tan, Sqrt Cos, Sin, Tan, Sqrt COS, SIN, TAN, SQRT
Math functions 2^3 Power(2, 3) POWER(2,3)
Exponentiation Min, Max, Sum, Min, Max, Sum, Count, MIN, MAX, SUM,
Aggregation Count, Avg, StDev, Var, COUNT,
31
D
Query04_Fig24a
Subtotals (Where)
A
T Animal
AnimalID
SELECT Count(AnimalID) AS CountOfAnimalID
A
Name
Category FROM Animal
Breed WHERE (Category = Cat);
DateBorn
B Field
Gender
AnimalID Category
A
Table Animal Animal
Total Count Where
Sort
S Criteria
Or
Cat
32
D
Query04_Fig24
T
Breed
DateBorn
Gender Category CountOfAnimalID
Dog 100
A Field
Table
Category
Animal
AnimalID
Animal
Cat
Bird
Fish
47
15
14
B
Total Group By Count Reptile 6
Sort Descending Mammal 6
Spider 3
Criteria
A Or
S
SELECT Category, Count(AnimalID) AS CountOfAnimalID
FROM Animal
GROUP BY Category
ORDER BY Count(AnimalID) DESC;
Animal
Conditions on Totals (Having)
A AnimalID
Name
Category
Dog
CountOfAnimalID
100
Category
T
Cat 47
Breed Bird 15
DateBorn Fish 14
Gender
B Total
Sort
Group By Count
Descending
each Category, but only list
them if more than 10.
A Criteria
Or
>10
S SELECT
FROM
GROUP BY
Category, Count(AnimalID) AS CountOfAnimalID
Animal
Category
E HAVING
ORDER BY
Count(AnimalID) > 10
Count(AnimalID) DESC;
34
D
Query04_Fig26
Animal
Where (Detail) v Having (Group)
A AnimalID
Name CategoryCountOfAnimalID
T
Category Dog 30
Breed Cat 18
DateBorn
Gender
A Field
Table
Category
Animal
AnimalID
Animal
DateBorn
Animal
Count Animals born
after 6/1/2007 in
each Category, but
B Total
Sort
Group By Count
Descending
Where only list Category
if more than 10.
A Criteria
Or
>10 >01-Jun-2007
S SELECT
FROM
WHERE
Category, Count(AnimalID) AS CountOfAnimalID
Animal
DateBorn > 01-Jun-2007
E GROUP BY
HAVING
ORDER BY
Category
Count(AnimalID) > 10
Count(AnimalID) DESC;
35
D
Query04_Fig27
T
who bought something between 8
EmployeeID
CustomerID
01-Apr-2004 and 31-May-2004. 14
SalesTax 19
A Field
Table
CustomerID SaleDate
Sale Sale
22
24
28
B Sort
Criteria
Ascending
Between 01-Apr-2007
36
37
38
A
And 31-May-2007 39
Or 42
50
E
And 31-May-2007) 74
ORDER BY CustomerID; 80
90
36
D
Query04_Fig28
Joining Tables
A SaleID
Sale Customer
CustomerID CustomerID LastName
A
42 Froedge
Field CustomerID LastName SaleDate 63 Grimes
74 Hinton
Table Sale Customer Sale
36 Holland
B Sort
Criteria
Ascending
Between 01-Apr-2007
6
50
58
Hopkins
Lee
McCain
And 31-May-2007
A Or
S
SELECT DISTINCT Sale.CustomerID, Customer.LastName
FROM Customer
INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID
WHERE (SaleDate Between 01-Apr-2007 And 31-May-2007)
E ORDER BY Customer.LastName;
T
INNER JOIN table2
ON table1.column = table2.column
E Informal syntax
38
D Syntax for Three Tables
A SQL 92 syntax to join three tables
T FROM Table1
INNER JOIN Table2
A ON Table2.ColA = Table3.ColA
INNER JOIN Table3
B ON Table1.ColB = Table2.ColB
E
39
Query04_Fig30
A
Animal SaleAnimal Sale Customer
AnimalID SaleID SaleID CustomerID
Name AnimalID SaleDate Phone
T
Category SalePrice EmployeeID FirstName
Breed CustomerID LastName
A
Table
Sort
Customer
Ascending
Customer Animal Animal Animal Sale
B
Criteria Cat Is Not Null Like %White% Between 01-Jun-2007
And 31-Dec-2007
A
Or
S
E
41
D Building a Query
A List the Last Name and Phone of anyone who bought a registered
White cat between 6/1/04 and 12/31/04.
A
To connect Animal to Sale: SaleAnimal
Select the desired columns and test the query.
S
Enter the constraints.
Set Order By columns.
E
Add Group By columns.
Add summary computations to the SELECT statement.
42
D Joining Tables (Hints)
A Build Relationships First Multiple Tables
T Drag and drop
From one side to many side
FROM (Table1
INNER JOIN Table2
B FROM Table1
INNER JOIN Table2
Shorter Notation
FROM T1, T2, T3
A ON Table1.ColA = Table2.ColB
Join columns are often keys, but
JOIN T1.ColA = T2.ColB
T1.ColC = T3.ColD
Shorter Notation is not correct
S
they can be any columns--as
long as the domains (types of syntax, but it is easier to write.
data) match.
E
43
D Tables with Multiple Joins
A Potential problem with three or more tables.
Access uses predefined relationships to automatically
T determine JOINs.
JOINS might loop. AnimalOrder
A
OrderID
Most queries will not work with loops. OrderDate
ReceiveDate
SupplierID
ShippingCost
B
EmployeeID
A query with these four tables with
Supplier
four JOINS would only return 1 1
Employee
SupplierID
EmployeeID
rows where the Employee had the
A
Name
LastName
ContactName
same ZipCode as the Supplier. If Phone
City
FirstName
Phone
Address
you only need the Supplier city, ZipCode CityID
Address
ZipCode
S
CityID ZipCode
just delete the JOIN between City
CityID
TaxPayerID
Employee and ZipCode. If you State
AreaCode
DateHired
DateReleased
want both cities, add the ZipCode Population1990
E
Population1980
table again as a fifth table. Country
Latitude
Longitude
44
D Table Alias
A CityID
City Supplier
SupplierID
AnimalOrder
OrderDate
Employee
EmployeeID
City2
CityID
T
ZipCode Address SupplierID LastName ZipCode
City ZipCode ShippingCost ZipCode City
State CityID EmployeeID CityID State
S
4 7972 Middlesboro 5 James 7083 Orlando
2 10896 Springfield 1 Reeves 9201 Lincoln
4 7972 Middlesboro 3 Reasoner 8313 Springfield
9 10740 Columbia 8 Carpenter 10592 Philadelphia
45
D Saved Query: Create View
A
Save a query
T Faster: only enter once
Faster: only analyze once
CREATE VIEW Kittens AS
SELECT *
A SELECT Avg(ListPrice)
S FROM Kittens
WHERE (Color LIKE %Black%);
E
46
D Query04_Fig36
Updateable Views
A
T
SaleItem(SaleID, ItemID, Quantity) Merchandise(ItemID, Description)
E
47
Query04_Fig37
121 57 3
Merchandise(ItemID, Description)
57 Cat food
T 121
122
82
57
2
1
58
59
Dog food
Bird food
A
B SaleLine(SaleID, Item.ItemID, Description, Quantity)
121 57 Cat food 3
A 121
122
82
57
32
Bird feeder
Cat food
2
1
48
D SQL Syntax: ALTER TABLE
A ALTER TABLE table
T ADD COLUMN column datatype (size)
DROP COLUMN column
A
B
A
S See also:
CREATE TABLE
E DROP TABLE
49
D SQL Syntax: COMMIT
A COMMIT WORK
T
A
B
A
S See also: ROLLBACK
E
50
D SQL Syntax: CREATE INDEX
A CREATE [UNIQUE] INDEX index
T ON table (column1, column2, )
WITH {PRIMARY | DISALLOW NULL | IGNORE NULL}
A
B
A
S See also: CREATE TABLE
E
51
D SQL Syntax: CREATE TABLE
A CREATE TABLE table
T (
column1 datatype (size) [NOT NULL] [index1] ,
A column2
,
datatype (size) [NOT NULL] [index2],
A
REFERENCES existing_table (key_column)
ON DELETE CASCASDE
)
S See also:
ALTER TABLE
E DROP TABLE
52
D SQL Syntax: CREATE VIEW
A CREATE VIEW viewname AS
T SELECT
A
B
A
S See also: SELECT
E
53
D SQL Syntax: DELETE
A DELETE
T FROM table
WHERE condition
A
B
A
S See also: DROP
E
54
D SQL Syntax: DROP
A DROP INDEX index ON table
T DROP TABLE
A DROP VIEW
B
A
S See also: DELETE
E
55
D SQL Syntax: INSERT
A INSERT INTO table (column1, column2, )
T VALUES (value1, value2, )
B
A
S See also: SELECT
E
56
D SQL Syntax: GRANT
A GRANT privilege privileges
T ON object
TO user | PUBLIC
ALL, ALTER, DELETE, INDEX,
INSERT, SELECT, UPDATE
A
B
A
S See also: REVOKE
E
57
D SQL Syntax: REVOKE
A REVOKE privilege privileges
T ON object
FROM user | PUBLIC
ALL, ALTER, DELETE, INDEX,
INSERT, SELECT, UPDATE
A
B
A
S See also: GRANT
E
58
D SQL Syntax: ROLLBACK
A SAVEPOINT savepoint {optional}
T ROLLBACK WORK
A TO savepoint
B
A
S See also: COMMIT
E
59
D SQL Syntax: SELECT
A SELECT DISTINCT table.column {AS alias} , . . .
FROM table/query
T INNER JOIN table/query ON T1.ColA = T2.ColB
WHERE (condition)
A GROUP BY column
HAVING (group condition)
B ORDER BY table.column
{ UNION, INTERSECT, EXCEPT }
A
S
E
60
D SQL Syntax: SELECT INTO
A SELECT column1, column2,
T INTO newtable
FROM tables
A WHERE condition
B
A
S See also: SELECT
E
61
D SQL Syntax: UPDATE
A UPDATE TABLE table
T SET column1 = value1, column2 = value2,
WHERE condition
A
B
A
S See also: DELETE
E
62