为啥 MySql 会出现“子查询返回超过 1 行”错误?
Posted
技术标签:
【中文标题】为啥 MySql 会出现“子查询返回超过 1 行”错误?【英文标题】:Why does MySql give "Subquery returns more than 1 row" error?为什么 MySql 会出现“子查询返回超过 1 行”错误? 【发布时间】:2009-05-14 14:31:07 【问题描述】:嗨,伙计,我正在从我的表格中选择我的活动记录,我的所有其他记录都很好,但活动记录给我错误,我的代码是
@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, "+ "(从庄园 e 中选择 e.active,其中 e.active = true AND #filter_estates) 作为庄园状态,"+ "(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 Estates e LEFT JOINGovernance_bodies g on e.governing_body_id = g.id AND #filter_estates "
我得到一个错误。
(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) as total_stands, (select e.active from states e where e.active = true AND e.id IS NOT NULL) as estate_status, (select count() from services sp where sp .estate_id = e.id AND e.id IS NOT NULL) as service_providers,(select count(*) from approved_vendors av where av.estate_id = e.id AND e.id IS NOT NULL) as vendor FROM states e LEFT JOINGovernance_bodies g on e.governing_body_id = g.id AND e.id IS NOT NULL ):
我想显示所有活跃和不活跃的庄园。
请问各位,我该如何解决这个问题。我正在使用 Mysql 数据库。
【问题讨论】:
【参考方案1】:看来您的第三行可能有问题:
(从庄园 e 中选择 e.active,其中 e.active = true AND #filter_estates)作为庄园状态
上面和下面的行使用聚合,所以它们只返回一行,这可能(可能是)返回多行并且它不知道将哪一行分配给 Estate_status。
您可能只需将该行更改为:
e.active as Estate_status
【讨论】:
我在写回复时走神了。 ;) +1 谢谢,这个“(选择 e.active)as Estate_status”有效。祝你有美好的一天。【参考方案2】:我当然不熟悉该表,所以我现在能给你的最佳答案是为什么该查询不起作用。
从庄园 e 中选择 e.active,其中 e.active = true AND #filter_estates) 作为庄园状态
该行返回多行,您不能在那里执行此操作。请注意,您的其他人使用聚合函数,因此它们只返回一行。
哦,我不怎么使用 My SQL,但是在 T-SQL 中我们经常做 max(e.active) 之类的事情,或者可能会放一个 top 1(我认为这是我的 SQL 中的 Limit 1)
【讨论】:
【参考方案3】:您的子查询
(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 ...
【讨论】:
【参考方案4】: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
【讨论】:
以上是关于为啥 MySql 会出现“子查询返回超过 1 行”错误?的主要内容,如果未能解决你的问题,请参考以下文章
需要 SQL Query 帮助并显示错误消息子查询返回超过 1 行