Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Emanuel Gustafzon
Emanuel Gustafzon

Posted on

     

SQL Course: Many-to-many relationship and Nested Joins.

You have learned about one-to-one and one-to-many relationships and they are quite straight forward. Many-to-Many works a bit different because you need an extra table, so called join table.

In this example we will let users like posts in the database. To achieve this functionality we need to create a many-to-many relationship because a user can like many posts and a post can have many likes.

To establish this relationship we need a join table that holds a reference to the user who likes the post and the post that is being liked.

Create a likes table that function as a join table.

CREATE TABLE Likes(  ID INTEGER PRIMARY KEY AUTOINCREMENT,  PostID INTEGER,  UserID INTEGER,   FOREIGN KEY (PostID) REFERENCES Posts(ID),  FOREIGN KEY (UserID) REFERENCES Users(ID));
Enter fullscreen modeExit fullscreen mode

Insert data to the likes table.

We add the user’s ID and the post’s ID. Ex user 1, Ben likes post 1 about sql.

INSERT INTO Likes (UserID, PostID) VALUES  (1, 1),  (2, 1),  (3, 1),   (1, 2),  (2, 2),  (3, 3);
Enter fullscreen modeExit fullscreen mode

Nested Join

To be able to query data from a many-to-many relationship we need nested joins.

  1. Select the fields to retrieve.
  2. Use the join table as starting point, our likes table.
  3. Join the related data, in our case the users and the posts.
SELECT u.Username, p.Title, p.ContentFROM Likes lJOIN Users u ON l.UserID = u.IDJOIN Posts p ON l.PostID = p.ID;
Enter fullscreen modeExit fullscreen mode

To make the result more readable let’s group users and the posts they liked together.

SELECT u.Username, p.Title, p.ContentFROM Likes lJOIN Users u ON l.UserID = u.IDJOIN Posts p ON l.PostID = p.IDGROUP BY u.ID, p.ID;
Enter fullscreen modeExit fullscreen mode

Result:

Ben | sql | sql content
Ben | java | java content
Jim | sql | sql content
Jim | java | java content
Luk | sql | sql content
Luk | NLP | NLP content

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Hi 👋, I am a passionate developer and I am looking forward to sharing my knowledge here on Dev. It’s great for myself and others to get a deeper understanding of software development.
  • Location
    Gothenburg, Sweden
  • Education
    Code Institute and .Net Developer at EC Utbildningen
  • Joined

More fromEmanuel Gustafzon

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp