Many-to-Many Joins and Bridge Tables

Many-to-many SQL join patterns with bridge tables, aggregation, filtering, and index guidance.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Many-to-many joins
Join through a bridge table
SELECT u.user_id, u.email, r.role_name
FROM users u
JOIN user_roles ur ON ur.user_id = u.user_id
JOIN roles r ON r.role_id = ur.role_id;

# Resolve many-to-many relationships with two joins.

Aggregate across a many-to-many relationship
SELECT p.post_id, p.title, COUNT(pt.tag_id) AS tag_count
FROM posts p
LEFT JOIN post_tags pt ON pt.post_id = p.post_id
GROUP BY p.post_id, p.title;

# Count related entities after joining through the bridge.

Find posts with all required tags
SELECT pt.post_id
FROM post_tags pt
JOIN tags t ON t.tag_id = pt.tag_id
WHERE t.name IN ('sql', 'performance')
GROUP BY pt.post_id
HAVING COUNT(DISTINCT t.name) = 2;

# Join and group, then compare distinct matched tags to the required count.

## Design notes
Index bridge-table foreign keys
CREATE INDEX idx_user_roles_user_id ON user_roles(user_id);
CREATE INDEX idx_user_roles_role_id ON user_roles(role_id);

# Index both sides of the relationship for join speed.

Recommended next

No recommendations yet.