Docsity

SQL Queries for Joining Tables: Natural Join, Outer Join, and Querying Student-Music Data, Slides of Introduction to Computers

Partial preview of the text

Download SQL Queries for Joining Tables: Natural Join, Outer Join, and Querying Student-Music Data and more Slides Introduction to Computers in PDF only on Docsity!

Display Order

SELECT name, id FROM student ;

WHERE sex="M" AND class="1A" ORDER BY name

eg. 16 List the boys of class 1A, order by their names. name id Peter 9801 Johnny 9803 Luke 9810 Bobby 9811 Aaron 9812 Ron 9813

ORDER BY

dcode name id Aaron 9812 Bobby 9811 Johnny 9803 Luke 9810 Peter 9801 Ron 9813 Result

Display Order

SELECT name, id, class, dcode FROM student ;

WHERE class="2A" ORDER BY dcode

eg. 17 List the 2A students by their residential district. name id class dcode Jimmy 9712 2A HHM Tim 9713 2A HHM Samual 9714 2A SHT Rosa 9703 2A SSP Helen 9702 2A TST Joseph 9715 2A TSW Paula 9701 2A YMT Susan 9704 2A YMT

Result

Multiple Tables:

field

A

B

field

field1 field

A

A

A

1 2 3 B B B

Each student should learn a musical instrument.

Two database files: student.dbf & music.dbf

The common field: student id

field type width contents

id numeric 4 student id number

type character 10 type of the music instrument

The Situation:

Music Lesson

The Situation:

Music Lesson

SELECT A

USE student

SELECT B

USE music

Natural Join

Music id 9801 type Student 9801 id name class 9801 Product id name (^) class type Same id

Join

eg. 25 Make a list of students and the instruments they learn. (Natural Join)

SELECT s.class, s.name, s.id, m.type ;

FROM student s, music m ;

WHERE s.id=m.id ORDER BY class, name

Natural Join

class name id type 1A Aaron 9812 Piano 1A Bobby 9811 Flute 1A Gigi 9824 Recorder 1A Jill 9820 Piano 1A Johnny 9803 Violin 1A Luke 9810 Piano 1A Mary 9802 Flute : : : :

Result

eg. 25 Make a list of students and the instruments they learn. (Natural Join)

Natural Join

Music Student Product

Join

Condition

m.type= "Piano"

Group By

class

eg. 26

eg. 26 Find the number of students learning piano in each class.

SELECT s.class, COUNT(*) ;

FROM student s, music m ;

WHERE s.id=m.id AND m.type="Piano" ;

GROUP BY class ORDER BY class

Natural Join

class cnt 1A 4 1B 2 1C 1

Result

eg. 27 List the students who have not yet chosen an instrument. (No match)

Outer Join

No match Music id type Student 9801 id name class

eg. 27 List the students who have not yet chosen an instrument. (No match)

SELECT class, name, id FROM student ;

WHERE id NOT IN ( SELECT id FROM music ) ;

ORDER BY class, name

Outer Join

Result

class name id 1A Mandy 9821 1B Kenny 9814 1B Tobe 9805 1C Edmond 9818 1C George 9817 : : :

Outer Join

Natural Join No Match Outer Join

eg. 28

SELECT s.class, s.name, s.id, m.type ;

FROM student s, music m ;

WHERE s.id=m.id ;

Outer Join

UNION ;

SELECT class, name, id, "" ;

FROM student ;

WHERE id NOT IN ( SELECT id FROM music ) ;

ORDER BY 1, 2

eg. 28