I believe FK is referring to look-up tables in terms of bridging entites in many-to-may realationships; ie, a Song may have a many-to-many relationship to Album (An Album has many Songs and a Song may appear on many albums). So your relational schema will require the tables Song, Album, and the "lookup table" Song_Album whose rows contain foreign keys to SongTitle and Album records.
If I get the gist of what you are asking FK, the way you use these relationships in your queries is through joins. A join between two tables produced a set which is the product of the two sets being joined. For example, if we have table X with the values with the records {X1, X2 X3} and table Y which contains the records {Y1, Y2, Y3} and we join the two tables we get these results:
Code:
Table X
-------
X1
X2
X3
and
Table Y
-------
Y1
Y2
Y3
and we join these two tables we get
Table X . Table Y
---------------
X1 Y1
X1 Y2
X1 Y3
X2 Y1
X2 Y2
X2 Y3
X3 Y1
X3 Y2
X3 Y3
So what's this gotto do with your question?
OK, lets say you want to find the details of all the CDs that contain a certain song and you have the following database schema:
Code:
Song
-----
ID
name
length
primary key = ID
Album
------
ID
name
length
primary key = ID
Now the relationship between Song and Album is many-to-many, so you need the bridging entity Song_Album.
Code:
Song_Album
-----------
songID
albumID
primary key = songID, albumID
Note that for Song_Album I have specified a "composite" key; that is, for each record the combination of songID and albumID must be unique.
Now, to find the details (Album.name, Album.length) of all albums that a certain song (Song.name) appears on I would write the following query which "joins" the three tables Album, Song and Song_Album. Using php the song name to search for is stored in $songName.
Code:
$sql = "
SELECT Album.name AS albumName, Album.length AS albumLength
FROM Song, Album, Song_Album
WHERE Album.ID = albumID
AND Song.ID = songID
AND Song.name = '$songName' ";
The "FROM" clause joins the three tables creating a mega "table" which is the product of all three tables (as explained above).
The "WHERE" clause tells the sql server to narrow down the result set to just those records in Album which have a relationship to entries in Song_Album which in turn have a relationship to records in Song which have a name that matches $songName !
Note that in the WHERE clause I use both the table name and column name to identify Song.ID and Album.ID. This is to avoid the ambiguity that arises from both Song and Album having an attribute "ID". If I had ommitted this, when I send the sql string in a query, the sql server would return an error.
Note I haven't considered performance issues in the syntax of my query.
Look through the resent postings in this forum as somewhere I've given some urls to an online tutorial and book on SQL.
Bookmarks