Reputation:
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
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
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