简体   繁体   English

Rails和Mysql-优化和重新定义查询

[英]Rails & Mysql - Optimize and rephrase query

Thanks to this answer to a previous question of mine and this article I found a way to rephrase this query: 由于我的上一个问题得到了这个答案因此本文找到了一种改写此查询的方法:

SELECT * FROM participants
GROUP BY conversation_id
HAVING sum(user_id not in (1,3)) = 0

to this Rails style query: 对此Rails样式查询:

Participant.find(:all, group: "conversation_id HAVING sum(user_id not in (1,3)) = 0")

I am new to Rails, but it seems to me that this is old syntax - what bothers me the most is that I use a lot of sql in there, instead of doing it all in Rails syntax. 我是Rails的新手,但在我看来,这是旧语法-最让我感到困扰的是,我在其中使用了很多sql,而不是全部使用Rails语法。

How can I rephrase the query above even more so that it is only written in Rails syntax, possibly without any need for quotation marks? 我该如何重新改写上面的查询,使其仅以Rails语法编写,而可能不需要引号? I need to make sure that this will run with different databases. 我需要确保它可以与其他数据库一起运行。

The Rails 3 way would be: Rails 3的方式是:

Participant.group("conversation_id").having("sum(user_id not in (1,3)) = 0")

You won't be able to do away with strings in the having clause. 您将无法在hading子句中删除字符串。 What's your concern with strings? 您对琴弦有什么担心? The query above should be fairly portable. 上面的查询应该相当可移植。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM