Professional Documents
Culture Documents
Vidya kumari
Joining Tables
• So far, all the queries you’ve seen have been concentrated on a single
table.
• But SQL also allows you to query two or more tables at a time, and display a
combined result set.
• This is technically referred to as a join, since it involves “joining” different
tables at common fields (the foreign keys) to create new views of the data.
Here’s an example of joining the songs and artists tables together using the
common artist_id field (the WHERE clause is used to map the common fields
to each other):
mysql> SELECT song_id, song_title, artist_name FROM songs, artists
-> WHERE songs.fk_song_artist = artists.artist_id;
+---------+---------------------------+-------------+
| song_id | song_title | artist_name |
+---------+---------------------------+-------------+
| 1 | Janie's Got A Gun | Aerosmith |
| 2 | Crazy | Aerosmith |
| 8 | Gimme Gimme Gimme | Abba |
| 9 | SOS | Abba |
| 10 | Dancing Queen | Abba |
| 11 | Voulez Vous | Abba |
| 7 | Apologize | Timbaland |
| 4 | Sure | Take That |Chapter 7: Working with Databases and SQL 199
| 5 | Pray | Take That |
| 6 | Another Crack In My Heart | Take That |
| 12 | Babe | Take That |
| 3 | En Las Delicious | Cubanismo |
+---------+---------------------------+-------------+
12 rows in set (0.00 sec)
And here’s an example of joining all three tables together and then filtering the
result set even further to include only those songs with a rating of 4 or higher and
with non-U.S. artists:
+------------------+-------------+-------------+
| song_title | artist_name | rating_name |
+------------------+-------------+-------------+
| En Las Delicious | Cubanismo | Excellent |
| Pray | Take That | Good |
| SOS | Abba | Good |
| Dancing Queen | Abba | Good |
+------------------+-------------+-------------+
4 rows in set (0.02 sec)
Modifying and Removing Records
Just as you INSERT records into a table, so too can you delete records with
the DELETE statement.
Typically, you would select a specific subset of rows to be deleted by adding
the WHERE clause to the DELETE statement, as in the next example, which
deletes all those songs with a rating less than or equal to 3:
mysql> DELETE FROM songs
-> WHERE fk_song_rating <= 3;
Query OK, 5 rows affected (0.02 sec)
There’s also an UPDATE statement, which can be used to change the
contents of a record; this too accepts a WHERE clause, so that you can apply
changes to only those records matching specific criteria.
Consider the following example, which changes the rating 'Excellent' to
'Fantastic’: