SQL 使用 Rails 模型作为参考的多连接查询
SQL query with multiple joins using Rails models as reference
我想select统计survey.property.address.city == "Garrison"
所在的所有调查。我有以下型号:
Survey
many_to_one :property
Property
one_to_many :surveys
many_to_one :address
Address
one_to_many :properties
如何使用SQL查询?
SELECT count(*) FROM surveys JOIN...
假设您的 table 被命名为 rails 将命名这些对象并且您拥有关系隐含的外键:
SELECT
COUNT(*)
FROM
surveys
JOIN
properties ON surveys.property_id = properties.id
JOIN
addresses ON addresses.id = properties.address_id
WHERE
addresses.city = 'Garrison'
你的关系定义也很奇怪......我假设这只是一个表达关系的伪代码版本。
编辑:我更正了第二个连接,因为我相信我的关系是倒过来的。
我想select统计survey.property.address.city == "Garrison"
所在的所有调查。我有以下型号:
Survey
many_to_one :property
Property
one_to_many :surveys
many_to_one :address
Address
one_to_many :properties
如何使用SQL查询?
SELECT count(*) FROM surveys JOIN...
假设您的 table 被命名为 rails 将命名这些对象并且您拥有关系隐含的外键:
SELECT
COUNT(*)
FROM
surveys
JOIN
properties ON surveys.property_id = properties.id
JOIN
addresses ON addresses.id = properties.address_id
WHERE
addresses.city = 'Garrison'
你的关系定义也很奇怪......我假设这只是一个表达关系的伪代码版本。
编辑:我更正了第二个连接,因为我相信我的关系是倒过来的。