我有这些表格:
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')
但是这个查询不起作用。
答案 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;