avoid
avoid

Reputation: 1

Select different columns from joined tables

How do I select the id, user_id specifically from the comments table and how do I select username, date, posts from the users table specifically?

here is the code.

SELECT users.*, comments.*

Upvotes: 0

Views: 148

Answers (5)

laurent
laurent

Reputation: 908

Based on your question, I suppose you don't know what to put in the WHERE [something] in the other answers.

SELECT c.id, c.user_id, u.username, u.date, u.posts 
FROM comments c, users u 
WHERE c.user_id = u.id

Assuming the user id field in users table is called id.

You could use also:

SELECT c.id, c.user_id, u.username, u.date, u.posts 
FROM users u 
INNER JOIN comments c ON c.user_id = u.id

Anyways, this will solve your problem but I would recommend some MySQL (or SQL in general) readings like MySql Manual

Upvotes: 0

Hao
Hao

Reputation: 8115

Don't forget to use join, Dan's answer would result to cartesian product (i.e. table comma table) if you inadvertently forgot to put the joining condition in WHERE clause

SELECT c.id, c.user_id, u.username, u.date, u.posts 
FROM comments c join users u using(user_id)
WHERE [something]

Upvotes: 0

klox
klox

Reputation: 2093

"SELECT id, user_id FROM comments";
"SELECT username, date, posts FROM users";

Upvotes: 0

Dan D.
Dan D.

Reputation: 1127

SELECT c.id, c.user_id, u.username, u.date, u.posts 
    FROM comments c, users u 
    WHERE [something]

Upvotes: 2

Yisroel
Yisroel

Reputation: 8174

Heres a good reference for you MySQL SELECT Syntax

Upvotes: 1

Related Questions