给出以下消息表:
Column | Type |
-----------------+-----------------------------+-
id | integer |
body | text |
conversation_id | integer |
user_id | integer |
inserted_at | timestamp without time zone |
updated_at | timestamp without time zone |
sid | character varying(255) |
status | character varying(255) |
我正在尝试在Ecto中创建以下SQL查询:
SELECT COUNT(conversation_id) FROM messages m1 WHERE m1.id = ANY(SELECT MAX(m2.id) FROM messages m2 GROUP BY m2.conversation_id) AND status = 'received';
我试过了:
query = Message
|> where([m], m.id in fragment("ANY(select max(m2.id) from messages m2 group by m2.conversation_id)") and m.status = "received")
|> select([m], count(m.conversation_id))
但是我遇到了运行时错误:
** (Protocol.UndefinedError) protocol Ecto.Queryable not implemented for BlackMamba.Resolver.Message, the given module is not queryable
(ecto) lib/ecto/queryable.ex:33: Ecto.Queryable.Atom.to_query/1
(ecto) lib/ecto/query/builder/filter.ex:46: Ecto.Query.Builder.Filter.apply/3
(black_mamba) web/resolver/conversation.ex:56: BlackMamba.Resolver.Conversation.needs_response_conversation_count/2
非常感谢任何提示。
答案 0 :(得分:1)
我从未使用过fragment/1
,但正如错误消息所示,第一个参数(您传递的参数是sql_fragment
)必须是关键字列表(此列表[abc: 1, def: 2]
)你正在传递一个字符串。
Ecto清理所有原始SQL以防止SQL注入。