Introduction
When designing a database, it can be hard to organize all the information clearly. The Entity-Relationship model helps by showing how different pieces of data connect and relate to each other in a simple way.
Imagine a school where students enroll in classes. Each student has a unique ID and personal details. Classes have names and schedules. The enrollment shows which students attend which classes, and how many students can be in each class.
┌─────────┐ Enrolls ┌─────────┐
│ Student │─────────────────────│ Class │
└─────────┘ └─────────┘
│ │
│ │
▼ ▼
[StudentID, Name, Age] [ClassID, Name, Time]import sqlite3 conn = sqlite3.connect(':memory:') cur = conn.cursor() # Create tables for entities cur.execute('CREATE TABLE Student (StudentID INTEGER PRIMARY KEY, Name TEXT, Age INTEGER)') cur.execute('CREATE TABLE Class (ClassID INTEGER PRIMARY KEY, Name TEXT, Time TEXT)') # Create table for relationship cur.execute('CREATE TABLE Enrollment (StudentID INTEGER, ClassID INTEGER, ' 'FOREIGN KEY(StudentID) REFERENCES Student(StudentID), ' 'FOREIGN KEY(ClassID) REFERENCES Class(ClassID))') # Insert sample data cur.execute("INSERT INTO Student VALUES (1, 'Alice', 20)") cur.execute("INSERT INTO Class VALUES (101, 'Math', '9AM')") cur.execute("INSERT INTO Enrollment VALUES (1, 101)") # Query to show relationship cur.execute('''SELECT Student.Name, Class.Name FROM Student JOIN Enrollment ON Student.StudentID = Enrollment.StudentID JOIN Class ON Class.ClassID = Enrollment.ClassID''') for row in cur.fetchall(): print(row)