user984621
user984621

Reputation: 48453

SQL - how to get data from two tables

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.

Upvotes: 0

Views: 519

Answers (3)

andrewsha
andrewsha

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

timod
timod

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

Moyed Ansari
Moyed Ansari

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

Related Questions