SQL - 如何从两个表中获取数据

时间:2012-06-20 13:16:19

标签: sql ruby-on-rails postgresql

我有这些表格:

表-A

user_id
article_id
created_at

制品

user_id
created_at
...

我需要从相应用户的两个表中获取所有行(例如 user_id = 1 )并按列created_at对其进行排序。怎么做?

我试过这样做:

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

但是这个查询不起作用。

3 个答案:

答案 0 :(得分:1)

试试这个

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

答案 1 :(得分: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;

答案 2 :(得分:1)

我会尝试以下查询: 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;