Multi-table Databases and Joins

CSE 190 M (Web Programming) Spring 2008

University of Washington

References: SQL syntax reference, w3schools tutorial

Except where otherwise noted, the contents of this presentation are © Copyright 2008 Marty Stepp, Jessica Miller, and Amit Levy, and are licensed under the Creative Commons Attribution 2.5 License.

Valid XHTML 1.1 Valid CSS!

Lecture outline

HTML tables

displaying data in tables of rows and columns

Tables: <table>, <tr>, <td>

A 2D table of rows and columns of data (block element)

<table>
	<tr><td>1,1</td><td>1,2 okay</td></tr>
	<tr><td>2,1 real wide</td><td>2,2</td></tr>
</table>
1,11,2 okay
2,1 real wide2,2

Headers, captions: <th>, <caption>

<table>
	<caption>My important data</caption>
	<tr><th>Column 1</th><th>Column 2</th></tr>
	<tr><td>1,1</td><td>1,2 okay</td></tr>
	<tr><td>2,1 real wide</td><td>2,2</td></tr>
</table>
My important data
Column 1Column 2
1,11,2 okay
2,1 real wide2,2

Styling tables

table { border: 2px solid black; caption-side: bottom; }
tr { font-style: italic; }
td { background-color: yellow; text-align: center; width: 30%; }
My important data
Column 1Column 2
1,11,2 okay
2,1 real wide2,2

The border-collapse property

table, td, th { border: 2px solid black; }
table { border-collapse: collapse; }
Without border-collapse
Column 1Column 2
1,11,2
2,12,2
With border-collapse
Column 1Column 2
1,11,2
2,12,2

The rowspan and colspan attributes

<table>
	<tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr>
	<tr><td colspan="2">1,1-1,2</td>
		<td rowspan="3">1,3-3,3</td></tr>
	<tr><td>2,1</td><td>2,2</td></tr>
	<tr><td>3,1</td><td>3,2</td></tr>
</table>
Column 1Column 2Column 3
1,1-1,21,3-3,3
2,12,2
3,13,2

Column styles: <col>, <colgroup>

<table>
	<col class="pinkhighlight" />
	<colgroup class="yellowhighlight">
		<col /><col />
	</colgroup>
	
	<tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr>
	<tr><td>1,1</td><td>1,2</td><td>1,3</td></tr>
	<tr><td>2,1</td><td>2,2</td><td>2,3</td></tr></table>
Column 1Column 2Column 3
1,11,21,3
2,12,22,3

Don't use tables for layout!


Database design

Choosing the proper tables and columns for a database

Database design principles

First database design

student_grades
nameemailcoursegrade
Bartbart@fox.comComputer Science 142B-
Bartbart@fox.comComputer Science 143C
Milhousemilhouse@fox.comComputer Science 142B+
Lisalisa@fox.comComputer Science 143A+
Lisalisa@fox.comComputer Science 190MA+
Ralphralph@fox.comInformatics 100D+

Second database design

students
idnameemail
123Bartbart@fox.com
456Milhousemilhouse@fox.com
888Lisalisa@fox.com
404Ralphralph@fox.com
courses
idname
10001Computer Science 142
10002Computer Science 143
10003Computer Science 190M
10004Informatics 100
grades
student_idcourse_idgrade
12310001B-
12310002C
45610001B+
88810002A+
88810003A+
40410004D+

Related tables and keys

students
idnameemail
123Bartbart@fox.com
456Milhousemilhouse@fox.com
888Lisalisa@fox.com
404Ralphralph@fox.com
courses
idname
10001Computer Science 142
10002Computer Science 143
10003Computer Science 190M
10004Informatics 100
grades
student_idcourse_idgrade
12310001B-
12310002C
45610001B+
88810002A+
88810003A+
40410004D+

Design question

students
idnameemail
123Bartbart@fox.com
456Milhousemilhouse@fox.com
888Lisalisa@fox.com
404Ralphralph@fox.com
courses
idname
10001Computer Science 142
10002Computer Science 143
10003Computer Science 190M
10004Informatics 100
grades
student_idcourse_idgrade
12310001B-
12310002C
45610001B+
88810002A+
88810003A+
40410004D+

Design answer

teachers
idname
1234Krabappel
5678Hoover
9012Stepp
courses
idnameteacher_id
10001Computer Science 1421234
10002Computer Science 1435678
10003Computer Science 190M9012
10004Informatics 1001234

Multi-table queries

Extracting and consolidating data from multi-table databases

Querying multi-table databases

When we have larger datasets spread across multiple tables, we need queries that can answer high-level questions such as:

To do this, we'll have to join data from several tables in our SQL queries.

Cross product with JOIN

SELECT column(s) FROM table1 JOIN table2;
SELECT * FROM students JOIN grades;

idnameemailstudent_idcourse_idgrade
123Bartbart@fox.com12310001B-
404Ralphralph@fox.com12310001B-
456Milhousemilhouse@fox.com12310001B-
888Lisalisa@fox.com12310001B-
123Bartbart@fox.com12310002C
404Ralphralph@fox.com12310002C
... (24 rows returned)

Joining with ON clauses

SELECT column(s) FROM table1
JOIN   table2 ON condition(s)
...
JOIN   tableN ON condition(s);
SELECT *
FROM   students
JOIN   grades ON id = student_id;

Join example

SELECT *
FROM   students
JOIN   grades ON id = student_id;
idnameemailstudent_idcourse_idgrade
123Bartbart@fox.com12310001B-
123Bartbart@fox.com12310002C
404Ralphralph@fox.com40410004D+
456Milhousemilhouse@fox.com45610001B+
888Lisalisa@fox.com88810002A+
888Lisalisa@fox.com88810003A+

Filtering columns in a join

SELECT name, course_id, grade
FROM   students
JOIN   grades ON students.id = student_id;
namecourse_idgrade
Bart10001B-
Bart10002C
Ralph10004D+
Milhouse10001B+
Lisa10002A+
Lisa10003A+

Giving names to tables

SELECT name, g.*
FROM   students s
JOIN   grades g ON s.id = g.student_id;
namestudent_idcourse_idgrade
Bart12310001B-
Bart12310002C
Ralph40410004D+
Milhouse45610001B+
Lisa88810002A+
Lisa88810003A+

Filtered join (JOIN with WHERE)

SELECT name, course_id, grade
FROM   students s
JOIN   grades g ON s.id = g.student_id
WHERE  s.id = 123;
namecourse_idgrade
Bart10001B-
Bart10002C

Multi-way join

SELECT c.name
FROM   courses c
JOIN   grades g ON g.course_id = c.id
JOIN   students bart ON g.student_id = bart.id
WHERE  bart.name = 'Bart' AND g.grade <= 'B-';
name
Computer Science 142

A suboptimal query

Improved query

Practice queries

IMDb database

actors
idfirst_namelast_namegender
433259WilliamShatnerM
797926BritneySpearsF
831289SigourneyWeaverF
...
movies
idnameyearrank
112290Fight Club19998.5
209658Meet the Parents20007
210511Memento20008.7
...
roles
actor_idmovie_idrole
433259313398Capt. James T. Kirk
433259407323Sgt. T.J. Hooker
797926342189Herself
...

IMDb query example

[stepp@webster ~]$ mysql -u stepp -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Server version: 5.0.45-log Source distribution

mysql> use imdb_small;
Database changed

mysql> select * from actors where first_name like '%mick%';
+--------+------------+-----------+--------+
| id     | first_name | last_name | gender |
+--------+------------+-----------+--------+
|  71699 | Mickey     | Cantwell  | M      | 
| 115652 | Mickey     | Dee       | M      | 
| 470693 | Mick       | Theo      | M      | 
| 716748 | Mickie     | McGowan   | F      | 
+--------+------------+-----------+--------+
4 rows in set (0.01 sec)

PHP IMDB example

# connect to IMDB (substitute your user name / pw)
$db = mysql_connect("localhost", "USERNAME", "PASSWORD");
if (!$db) {
	die("Connect failed: " . mysql_error());
}
if (!mysql_select_db("imdb")) {
	die("Selecting DB failed: " . mysql_error());
}

# query the database
$query = "SELECT * FROM actors WHERE first_name = 'Ezekiel'";
$results = mysql_query($query);
if (!$results) {
	die("SQL query failed:\n$query\n" . mysql_error());
}

# loop through each actor
while ($row = mysql_fetch_array($results)) {
?>
	<li>
		<?= $row["last_name"] ?>, <?= $row["first_name"] ?>
	</li>
<?php
}
?>

Practice problem: Movie search

Practice problem: Cast list for a movie

Write a PHP script that, when given a movie, shows the names of all female actors that appeared in it. (To do this, you will need to perform an SQL query with join operations.)

Development strategy