Reputation: 48453
I have these tables:
user_id
article_id
created_at
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.
Upvotes: 0
Views: 519
Reputation: 195
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;
Upvotes: 1
Reputation: 595
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;
Upvotes: 1
Reputation: 8461
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
Upvotes: 1