[英]how to write a join condition in Ruby on Rails?
what I'm trying to do is to write something like the next query: 我想要做的是编写类似于下一个查询的内容:
SELECT *
FROM Customers c
LEFT JOIN CustomerAccounts ca
ON ca.CustomerID = c.CustomerID
AND c.State = 'NY'
Notice that I'm not using any WHERE clause, but I need to my JOIN have a condition. 注意,我没有使用任何WHERE子句,但是我需要对JOIN有一个条件。 I cannot make it work in Ruby on Rails. 我无法使其在Ruby on Rails中工作。
Can you help me out? 你能帮我吗?
You can join the tables with LEFT JOIN
. 您可以使用LEFT JOIN
表。 Just pass the join condition in joins
and you will get the expected result 只要在joins
通过joins
条件,您将获得预期的结果
Customer.joins("LEFT JOIN CustomerAccounts
ON CustomerAccounts.CustomerID = Customers.CustomerID
AND Customers.State = 'NY'")
#=> SELECT * FROM Customers LEFT JOIN CustomerAccounts ON CustomerAccounts.CustomerID = Customers.CustomerID AND Customers.State = 'NY'
Note: just
.joins()
doesINNER JOIN
so you need to specify the join with condition 注意:只有.joins()
可以进行INNER JOIN
因此您需要使用条件指定INNER JOIN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.