0

I have these tables:

table_a

user_id
article_id
created_at

articles

user_id
created_at
...

I need to obtain all rows from both tables for the respective user (lets say user_id=1) and sorted them by the column created_at. How to do that?

I have tried to do it this way:

Model.find_by_sql('SELECT table_a.* FROM table_a JOIN articles ON articles.user_id = 1 WHERE table_a.user_id = 1')

But this query won't work.

4
  • ON articles.user_id = table_a.user_id You should tell how you join the tables Commented Jun 20, 2012 at 13:18
  • 2
    Please define won't work and give examples. Unexpected data, error messages, every time you run it the power in your office goes out and a purple goblin steals your mouse and keyboard? Commented Jun 20, 2012 at 13:19
  • If I think about the query now, the JOIN probably is not needed there... I just need to get all rows from both tables with user_id=1 Commented Jun 20, 2012 at 13:20
  • @user984621 I don't know your business model but usually you got User<-->UserArticles<-->Articles. Commented Jun 20, 2012 at 13:21

3 Answers 3

1

I would give a try to following query: SELECT table_a.*, articles.* FROM table_a JOIN articles ON articles.user_id = table_a.user_id WHERE table_a.user_id = 1 ORDER BY table_a.created_at ASC;

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

Comments

1

try this

SELECT table_a.* ,articles.*
FROM table_a 
LEFT JOIN articles ON articles.user_id = table_a.user_id 
WHERE table_a.user_id = 1
ORDER BY table_a. created_at

Comments

1
SELECT
  table_a.*
FROM 
 table_a
JOIN 
 articles 
ON 
 articles.user_id = table_a.user_id 
WHERE 
 table_a.user_id = 1
ORDER BY
 table_a.created_at ASC;

Comments

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.