Multiple Tables with Joins

Part 1 - Initial Set Up with Queries

Setting up our 3 tables for books/authors and the join table

Initial ERD (Entity Relationship Diagram)/Schema for ybooksdb

ybooks ERD - 3 tables

Using WWW SQL Designer to design your DB

Somewhat cleaned output from www SQL Designer

    CREATE TABLE `ybooks_authors` (
    `book_id` INTEGER UNSIGNED,
    `author_id` INTEGER UNSIGNED,
    `author_order` TINYINT NULL DEFAULT NULL,
    UNIQUE KEY (book_id,author_id)
    )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE `ybooks` (
      `book_id` INTEGER UNSIGNED AUTO_INCREMENT,
      `title` VARCHAR(200) NULL DEFAULT NULL,
      `yearpub` YEAR NULL DEFAULT NULL,
      PRIMARY KEY (`book_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE `yauthors` (
      `author_id` INTEGER UNSIGNED AUTO_INCREMENT,
      `first_name` VARCHAR(30) NULL DEFAULT NULL,
      `last_name` VARCHAR(30) NULL DEFAULT NULL,
      `whereborn` VARCHAR(10) NULL DEFAULT NULL,
      PRIMARY KEY (`author_id`)
    )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    ALTER TABLE `ybooks_authors` ADD FOREIGN KEY (book_id) REFERENCES `ybooks` (`book_id`);
    ALTER TABLE `ybooks_authors` ADD FOREIGN KEY (author_id) REFERENCES `yauthors` (`author_id`);

Now to do the inserts


    INSERT INTO ybooks(title,yearpub) values
    ('Black Holes','1984'),
    ('1984', '1954'),
    ('MySQL for Relaxation','2022'),
    ('Sorcerors Stone', '1999'),
    ('Spellng for Dummys', '2017');

    INSERT INTO yauthors (first_name,last_name,whereborn) values
    ('Steven','Hawking','Oxford'),
    ('George','Orwell','England'),
    ('Albert','Einstein','NJ'),
    ('J.K.','Rowling','England'),
    ('Phil','Waclawski','MI'),
    ('Stan','Lee', 'NY');

    NOTE: This is really a bad way to do this, this assumes that you have the exact same 
    PK values as I did, but we do not have procedures nor an interface at this point, so 
    we do not have a lot of choice.

    INSERT INTO ybooks_authors (book_id,author_id,author_order) values
    (1,1,1),
    (1,3,2),
    (1,6,3),
    (2,2,1),
    (2,4,2),
    (3,5,1),
    (4,4,1),
    (4,6,2),
    (5,5,1),
    (5,2,2);

Build your Query

Page last updated on 20210125

HTML 5 Validation CSS 3 Validation Web Accessibility EValuator