因为我比Rails更新,所以我采用了一种快捷方式来构建一个相当复杂的(对我来说)查询。
好消息:我的查询正常工作
坏消息:我坚持使用hackish代码并且无法弄清楚如何将动态变量放入其中(如果它像Rails友好格式那样应该很容易)。
这是我的查询(为便于阅读而分手):
ActiveRecord::Base.connection.select_all( "SELECT DISTINCT ps.* FROM merchants merch, product_sales ps, users u, user_merchant_relations umr, memberships m
INNER JOIN marketing_efforts me ON me.id = ps.marketing_effort_id
LEFT OUTER JOIN member_sales ms ON me.id = ms.marketing_effort_id
LEFT OUTER JOIN crm_sales cs ON me.id = cs.marketing_effort_id
WHERE ((me.start < '2013-05-26' AND me.end > '2013-05-26') OR (me.start < '2013-05-26' AND me.end IS NULL)) AND (me.num_avail IS NULL OR me.num_avail > 0) AND (me.gender IS NULL OR me.gender = u.gender OR u.gender IS NULL) AND ((u.birthdate > me.birthdate_start AND u.birthdate < me.birthdate_end) OR (u.birthdate > me.birthdate_start AND me.birthdate_end IS NULL) OR (me.birthdate_start IS NULL AND me.birthdate_end IS NULL) OR u.birthdate IS NULL) AND ((ms.member_id = m.member_id AND m.user_id = u.id) OR ms.member_id IS NULL) AND (cs.crm_tier_id = umr.crm_tier_id OR cs.crm_tier_id IS NULL) AND u.id = 3 AND merch.id = 1")
任何地方'2013-05-26'出现我需要放入Time.now。最后的u.id和merch.id也需要接受变量。
我以为我可以这样做:.S =?... Q =?.... L =?...“,价值,价值,价值)但是这不起作用。
更新
我在这里:
ProductSale.joins('INNER JOIN marketing_efforts ON marketing_efforts.id = product_sales.marketing_effort_id').joins('LEFT OUTER JOIN member_sales ON marketing_efforts.id = member_sales.marketing_effort_id').joins('LEFT OUTER JOIN crm_sales ON marketing_efforts.id = crm_sales.marketing_effort_id')
所以我正在处理所有连接,但我遇到的问题是,使用原始SQL,我可以轻松定义我需要访问的所有表...例如:
FROM merchants merch, product_sales ps, users u, user_merchant_relations umr, memberships m
而我不确定如何使用Rails执行此操作。结果,我得到FROM product_sales
:
ProductSale Load (0.3ms) SELECT "product_sales".* FROM "product_sales" INNER JOIN ....
所以,当我试着说,例如,users.id = 1
我得到了:
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: users.id:
有什么想法?谢谢。
答案 0 :(得分:0)
也许不是最好的方法,但它起作用并解决了主要问题(无法传递动态变量):
ProductSale.find_by_sql [ " QUE=?...R=?..Y=? ", value, value, value]