user4928200
user4928200

Reputation:

Problems with joining two tables in SQL

I have two tables. user(user_id, username, password, age) and comment(comment_id, comment, user_id(foreign key)).

I'm trying to get username from user, using the user_id provided in comment.

My query looks like this:

$sql = "SELECT username FROM user WHERE user_id = (SELECT user_id FROM comments)";

I'm getting null. Is my brain working poorly or is it something else I messed up?

I just want to display all comments after each other, with the username before it.

Upvotes: 1

Views: 57

Answers (2)

Emmanuel N
Emmanuel N

Reputation: 7449

Use IN instead of "=" .

    SELECT username FROM user WHERE user_id IN (SELECT user_id FROM comments);

OR you can use a proper join, something like:

    SELECT username FROM user,comments WHERE user.user_id = comments.user_id

Upvotes: 1

D Stanley
D Stanley

Reputation: 152501

That's not a join - a join would be:

$sql = "SELECT username FROM user u JOIN comments c ON u.user_id = c.user_id";

When you use a subquery with =, the subquery must return one value. To show all related records in a related table, use JOIN instead.

Upvotes: 1

Related Questions