GNU Info

Info Node: (mysql.info)example-Foreign keys

(mysql.info)example-Foreign keys


Next: Searching on two keys Prev: example-user-variables Up: Examples
Enter node , (file) or (file)node

Using Foreign Keys
------------------

You don't need foreign keys to join 2 tables.

The only thing MySQL doesn't do is `CHECK' to make sure that the keys
you use really exist in the table(s) you're referencing and it doesn't
automatically delete rows from table with a foreign key definition. If
you use your keys like normal, it'll work just fine:

     CREATE TABLE persons (
         id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
         name CHAR(60) NOT NULL,
         PRIMARY KEY (id)
     );
     
     CREATE TABLE shirts (
         id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
         style ENUM('t-shirt', 'polo', 'dress') NOT NULL,
         color ENUM('red', 'blue', 'orange', 'white', 'black') NOT NULL,
         owner SMALLINT UNSIGNED NOT NULL REFERENCES persons,
         PRIMARY KEY (id)
     );
     
     
     INSERT INTO persons VALUES (NULL, 'Antonio Paz');
     
     INSERT INTO shirts VALUES
     (NULL, 'polo', 'blue', LAST_INSERT_ID()),
     (NULL, 'dress', 'white', LAST_INSERT_ID()),
     (NULL, 't-shirt', 'blue', LAST_INSERT_ID());
     
     
     INSERT INTO persons VALUES (NULL, 'Lilliana Angelovska');
     
     INSERT INTO shirts VALUES
     (NULL, 'dress', 'orange', LAST_INSERT_ID()),
     (NULL, 'polo', 'red', LAST_INSERT_ID()),
     (NULL, 'dress', 'blue', LAST_INSERT_ID()),
     (NULL, 't-shirt', 'white', LAST_INSERT_ID());
     
     
     SELECT * FROM persons;
     +----+---------------------+
     | id | name                |
     +----+---------------------+
     |  1 | Antonio Paz         |
     |  2 | Lilliana Angelovska |
     +----+---------------------+
     
     SELECT * FROM shirts;
     +----+---------+--------+-------+
     | id | style   | color  | owner |
     +----+---------+--------+-------+
     |  1 | polo    | blue   |     1 |
     |  2 | dress   | white  |     1 |
     |  3 | t-shirt | blue   |     1 |
     |  4 | dress   | orange |     2 |
     |  5 | polo    | red    |     2 |
     |  6 | dress   | blue   |     2 |
     |  7 | t-shirt | white  |     2 |
     +----+---------+--------+-------+
     
     
     SELECT s.* FROM persons p, shirts s
      WHERE p.name LIKE 'Lilliana%'
        AND s.owner = p.id
        AND s.color <> 'white';
     
     +----+-------+--------+-------+
     | id | style | color  | owner |
     +----+-------+--------+-------+
     |  4 | dress | orange |     2 |
     |  5 | polo  | red    |     2 |
     |  6 | dress | blue   |     2 |
     +----+-------+--------+-------+


automatically generated by info2www version 1.2.2.9