Mysql::Error: Subquery returns more than 1 row:

喜夏-厌秋 提交于 2020-01-06 06:18:11

问题


In my rails app, I am running a sql query using find_by_sql() since I need subqueries. This works if I do either the first or second query but when I add them together with the AND, it starts complaining about more than 1 row in subquery.

I want all rows (records) returned that match the criteria. What needs to be fixed/changes here? What is telling mysql I only want 1 row?

Here is the resultant SQL as viewed in the rails log:

Mysql::Error: Subquery returns more than 1 row: select p.* from policies p 
 where exists (select 0 from status_changes sc join statuses s on sc.status_id = s.id
 where sc.policy_id = p.id
 and s.status_category_id = '1'
 and sc.created_at between '2009-03-10' and '2009-03-12')
 or exists
 (select 0 from status_changes sc join statuses s on sc.status_id = s.id
 where sc.created_at in
 (select max(sc2.created_at)
 from status_changes sc2
 where sc2.policy_id = p.id
 and sc2.created_at < '2009-03-10')
 and s.status_category_id = '1'
 and sc.policy_id = p.id) 
AND (select 0 from status_changes sc
 where sc.policy_id = p.id
 and sc.status_id = 7
 and sc.created_at between '2008-12-31' and '2009-03-12')
 or exists
 (select 0 from status_changes sc
 where sc.created_at in
 (select max(sc2.created_at)
 from status_changes sc2
 where sc2.policy_id = p.id
 and sc2.created_at < '2008-12-31')
 and sc.status_id = 7
 and sc.policy_id = p.id)

回答1:


This line:

AND (select 0 from status_changes sc

Shouldn't it be

AND exists (select 0 from status_changes sc



回答2:


Subqueries that return more than 1 row are not supported by any SQL server, as far as I am aware.



来源:https://stackoverflow.com/questions/637613/mysqlerror-subquery-returns-more-than-1-row

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