Course

Querying Multiple Tables - Solution

Given a Database setup like this:

CREATE TABLE Users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    age INT NOT NULL,
    createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

CREATE TABLE Posts (
  id INT PRIMARY KEY AUTO_INCREMENT,
  title VARCHAR(100) NOT NULL,
  content TEXT NOT NULL,
  createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  userId INT NOT NULL,
  FOREIGN KEY (userId) REFERENCES Users(id)
);


INSERT INTO Users (name, email, age) VALUES
("Oscar","oscar@email.com", 25),
("Mario","mario@email.com", 30),
("Andrea","andrea@email.com", 40);

INSERT INTO Posts (title,content,userId) VALUES
("My First Post","My Name is Oscar.",1),
("Mario's New Post","Mario's blog is online!",2),
("Mario's Second Post","Hi mom!",2),
("Why Andrea is the Best","Some Post content Here",3);

Here are the solution and expected answers:

  • From users who are 30 or older
SELECT * FROM Posts WHERE userId IN
(SELECT id FROM Users WHERE age>=30);
IDTitleContentcreatedAtupdatedAtuserID
2Mario's New PostMario's blog is online!2024-04-17 21:10:522024-04-17 21:10:522
3Mario's Second PostHi mom!2024-04-17 21:10:522024-04-17 21:10:522
4Why Andrea is the BestSome Post content Here2024-04-17 21:10:522024-04-17 21:10:523
  • From users who's name contains 'ar' anywhere in their name (HINT: Check the 'Like' Lesson)
SELECT * FROM Posts WHERE userId IN
(SELECT id FROM Users WHERE name LIKE "%ar%");
IDTitleContentcreatedAtupdatedAtuserID
1My First PostMy Name is Oscar2024-04-17 21:10:522024-04-17 21:10:521
2Mario's New PostMario's blog is online!2024-04-17 21:10:522024-04-17 21:10:522
3Mario's Second PostHi mom!2024-04-17 21:10:522024-04-17 21:10:522

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

What is an ORM?