简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM