Ecto Model - subquery in select

断了今生、忘了曾经 提交于 2019-12-10 10:19:26

问题


I need to make this SQL query with Ecto:

SELECT users.*, (select count(0) from money_transactions where from_id = users.id AND created_at > '2016-1-25 0:00:00.000000') as money_transactions_today_db FROM "users" WHERE "users"."client_token" = '123'

I try to do something like this but it doesn't work:

query = from users in Like4uElixir.User,
        where: users.client_token in ^tokens,
        select: {users, (from money_transactions in Like4uElixir.MoneyTransaction,
                            where: money_transactions.from_id == users.id,
                            select: count(0))}

Does Ecto support subqueries? If not, how can I execute the query?


回答1:


You can use query fragments:

query = from users in Like4uElixir.User,
        where: users.client_token in ^tokens,
        select: {users, (fragment("(SELECT COUNT(0) FROM money_transactions
                                    WHERE money_transactions.from_id == ?)", users.id))}

Although in this case the query can also be written using regular joins and group_by. Current support for subqueries in Ecto is limited.



来源:https://stackoverflow.com/questions/35000859/ecto-model-subquery-in-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!