我有两个表,table1
id name age occupation ssn_id
1 A 18 engineer 12
2 B 19 engineer 67
3 C 14 student 89
4 B 19 engineer 67
表2
id ssn_id limit hours
1 67 2 20
2 12 2 17
3 89 2 78
Expexted output
ssn_id limit count(*) occupation
67 2 2 engineer
SQL查询 -
select id, occupation, count(*) as TOTAL, `limit` from table1*table2 where table1.ssn_id = table2.ssn_id and occupation = 'engineer' group by table1.ssn_id having count(*) > `limit`
我想将此查询转换为Rails Active Record Query。我尝试过使用include但是我无法获得第二个表的列。
答案 0 :(得分:1)
如果你有Table1和Table2的模型,你可以使用这种方法:
Table1.
joins(:table2).
select("table1.id, table1.occupation, count(*) as TOTAL, table2.limit").
where(occupation: 'engineer').where("table1.ssn_id = table2.ssn_id").
group(table1.ssn_id).
having("count(*) > limit")