Many-to-many relations in RDBMS databases

后端 未结 3 1207
误落风尘
误落风尘 2020-12-18 05:35

What is the best way of handling many-to-many relations in a RDBMS database like mySQL?

Have tried using a pivot table to keep track of the relationships, but it lea

3条回答
  •  余生分开走
    2020-12-18 06:07

    Keep track of a many-to-many relationship in a table specifically for that relationship (sometimes called a junction table). This table models the relationship as two one-to-many relationships pointing in opposite directions.

    CREATE TABLE customer (
        customer_id VARCHAR NOT NULL,
        name VARCHAR NOT NULL,
        PRIMARY KEY (customer_id));
    
    CREATE TABLE publication (
        issn VARCHAR NOT NULL,
        name VARCHAR NOT NULL,
        PRIMARY KEY (issn));
    
    -- Many-to-many relationship for subscriptions.
    CREATE TABLE subscription (
        customer_id VARCHAR NOT NULL,
            FOREIGN KEY customer_id REFERENCES customer (customer_id),
        issn VARCHAR NOT NULL,
            FOREIGN KEY issn REFERENCES publication (issn),
        begin TIMESTAMP NOT NULL,
        PRIMARY KEY (customer_id, issn));
    

    You then use the junction table to join other tables through it via the foreign keys.

    -- Which customers subscribe to publications named 'Your Garden Gnome'?
    SELECT customer.*
    FROM customer
        JOIN subscription
            ON subscription.customer_id = customer.customer_id
        JOIN publication
            ON subscription.issn = publication.issn
    WHERE
        publication.name = 'Your Garden Gnome';
    
    -- Which publications do customers named 'Fred Nurk' subscribe to?
    SELECT publication.*
    FROM publication
        JOIN subscription
            ON subscription.issn = publication.issn
        JOIN customer
            ON subscription.customer_id = customer.customer_id
    WHERE
        customer.name = 'Fred Nurk';
    

提交回复
热议问题