0

I have two database tables, one is named "articles", and the other one is "users"

the structure of articles is as follows:

article_id    article_title    user_id

The structure of users is:

user_id    user_fullname     password

I wish to retrieve a list of all articles from the table "articles", but would like to attach each article's user_fullname. I think this may require "LEFT JOIN", so I made the following attempt in MySQL prompt.

> SELECT * FROM articles A LEFT JOIN users U on U.user_id = A.user_id;

but somehow I don't see the user_fullname printed out with this command. I need some help with the correct syntax. Thank you!

4
  • 1
    You only need a left join if there can be rows in the first table that have no matching row in the second table. Can an article really have a user_id that isn't in the users table? Commented Jun 12, 2014 at 21:06
  • 2
    But either way, the query you wrote should have worked. Can you make a sqlfiddle that demonstrates the problem? Commented Jun 12, 2014 at 21:07
  • We can assume "articles" contain user_id's that are always available in users table. Commented Jun 12, 2014 at 21:16
  • If you want help with this, you need to provide an example of the failure. What you wrote should work, even though it's not the optimal way to write it. Commented Jun 12, 2014 at 21:17

1 Answer 1

3

A full join seems more appropriate, each article must have an author, so there should be a corresponding entry in the users table:

SELECT *
FROM articles a 
   JOIN users u USING(user_id);

Note: USING here is the same as ON a.user_id = b.user_id and can only be used if the column name is the same in both tables.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for clarifying the using. Did have had a goole search for it, before i see the updated answer. This link explain it good: lornajane.net/posts/2012/sql-joins-with-on-or-using
While an inner join may be better, a left join should still work. This answer doesn't fix whatever problem he had with the original query.
The left join should work, but I would argue that it is incorrect. I couldn't re-create the issue they were having.
A further question: if I want to retrieve a single article from table "articles" with a given article_id, I would also like to retrieve its author from the table "users". I did this: SELECT * FROM articles A WHERE A.article_id=1 JOIN users U ON U.user_id = A.user_id, but it didn't work
You would need to add a WHERE clause that limits the result set to that article_id
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.