0

嗨,伙计,我正在从我的表格中选择我的活动记录,我的所有其他记录都很好,但是活动记录给了我错误我的代码是

@query = Estate.find_by_sql"SELECT (e.name) as estate_name, g.name asGovernance_body,"+ "(select count( ) from stand s where s.estate_id = e.id AND #{filter_estates}) as total_stands, "+ "(select e.active from states e where e.active = true AND #{filter_estates}) as Estate_status, "+ "(select count( ) from services sp where sp.estate_id = e.id AND #{filter_estates} ) as service_providers,"+ "(select count(*) from approved_vendors av where av.estate_id = e.id AND #{filter_estates})as vendor"+ " FROM states e LEFT JOINGoverning_bodies g on e.governing_body_id = g.id和 #{filter_states} "

我得到一个错误。

(Mysql::Error: Subquery return more than 1 row: SELECT (e.name) as estate_name, g.name asGovernance_body,(select count( ) from stand s where s.estate_id = e.id AND e.id IS NOT NULL)作为total_stands,(从estates e中选择e.active,其中e.active = true AND e.id IS NOT NULL)作为estate_status,(从服务sp中选择count(),其中sp.estate_id = e.id AND e.id不为空)作为service_providers,(从approved_vendors av 中选择计数(*),其中av.estate_id = e.id AND e.id 不为空)作为来自庄园的供应商e LEFT JOINGovernance_bodies g on e.governing_body_id = g.id AND e.id 不为空):

我想显示所有活跃和不活跃的庄园。

请问各位,我该如何解决这个问题。我正在使用 Mysql 数据库。

4

4 回答 4

3

看起来您的第三行可能有问题:

(从庄园 e 中选择 e.active,其中 e.active = true AND #{filter_estates})作为庄园状态

上面和下面的行使用聚合,因此它们只返回一行,这可能(可能是)返回多行并且它不知道将哪一行分配给 Estate_status。

您可能只需将该行更改为:

e.active 作为 Estate_status

于 2009-05-14T14:35:51.323 回答
1

我当然不熟悉该表,所以我现在可以给您的最佳答案是为什么该查询不起作用。

从庄园 e 中选择 e.active,其中 e.active = true AND #{filter_estates}) 作为庄园状态

该行返回多行,你不能在那里做。请注意,您的其他人使用聚合函数,因此它们只返回一行。

哦,我不怎么使用 My SQL,但是在 T-SQL 中,我们经常做 max(e.active) 之类的事情,或者可能放一个 top 1(我认为这是我的 SQL 中的 Limit 1)

于 2009-05-14T14:36:12.740 回答
0

SELECT 子句中的子查询必须仅返回 1 行和 1 列才能明确。这件作品产生超过 1 行:

"(select e.active from estates e where e.active = true AND #{filter_estates}) as estate_status

将其更改为

"(select first(e.active) from estates e where e.active = true AND #{filter_estates}) as estate_status
于 2009-09-11T08:01:31.073 回答
0

你的子查询

(SELECT e.active FROM estates e WHERE   ...) AS estate_status  

返回多个值。

如果可以,请使用“TOP 1”,例如:

SELECT e.name AS estate_name   ,
       g.name AS governing_body,
       (SELECT COUNT(*) FROM stands s            WHERE   ...) AS total_stands,
       (SELECT TOP 1 e.active FROM estates e     WHERE   ...) AS estate_status,
       (SELECT COUNT(*) FROM services sp         WHERE   ...) AS service_providers,
       (SELECT COUNT(*) FROM approved_vendors av WHERE   ...) AS vendors
FROM   estates e
LEFT 
JOIN   governing_bodies g ON  e.governing_body_id = g.id
                          AND ...
于 2009-05-14T14:41:52.307 回答