views:

1887

answers:

2

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)
+3  A: 

This line:

AND (select 0 from status_changes sc

Shouldn't it be

AND exists (select 0 from status_changes sc
Chry Cheng
you da man! - thanks
Streamline
A: 

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

Ian Kemp
This is nonsense.
Tomalak
Select id, name from user where id in ( Select id From active_user ) ?
Petruza