MySQL子查询返回多行

时间:2009-04-22 16:59:47

标签: sql mysql

我正在执行此查询:

SELECT
    voterfile_county.Name,
    voterfile_precienct.PREC_ID,
    voterfile_precienct.Name,
    COUNT((SELECT voterfile_voter.ID
FROM voterfile_voter
JOIN voterfile_household
WHERE voterfile_voter.House_ID = voterfile_household.ID
AND voterfile_household.Precnum = voterfile_precienct.PREC_ID)) AS Voters
FROM voterfile_precienct JOIN voterfile_county
WHERE voterfile_precienct.County_ID = voterfile_County.ID;

我试图让它返回这样的东西:

County_Name   Prec_ID   Prec_Name   Voters(Count of # of voters in that precienct)

但是,我收到错误:

  

#1242 - 子查询返回超过1行。

我尝试在子查询中放置COUNT语句,但语法错误无效。

4 个答案:

答案 0 :(得分:59)

如果出现错误:错误号1242子查询返回多行,尝试在子查询之前放置ANY。例如:

此查询返回错误:

SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);

这是一个很好的查询:

SELECT * FROM t1 WHERE column1 = ANY (SELECT column1 FROM t2);

答案 1 :(得分:13)

您可以在没有子查询的情况下尝试使用简单的组:

SELECT voterfile_county.Name, 
  voterfile_precienct.PREC_ID, 
  voterfile_precienct.Name, 
  count(voterfile_voter.ID)
FROM voterfile_county
JOIN voterfile_precienct 
  ON voterfile_precienct.County_ID = voterfile_County.ID
JOIN voterfile_household 
  ON voterfile_household.Precnum = voterfile_precienct.PREC_ID
JOIN voterfile_voter 
  ON voterfile_voter.House_ID = voterfile_household.ID 
GROUP BY voterfile_county.Name, 
  voterfile_precienct.PREC_ID, 
  voterfile_precienct.Name

当您使用GROUP BY时,您未分组的任何列必须具有聚合子句(fe SUM或COUNT。)因此,在这种情况下,您必须对县名,precienct.id和precient.name进行分组。 / p>

答案 2 :(得分:3)

试试这个

SELECT
voterfile_county.Name, voterfile_precienct.PREC_ID, 
voterfile_precienct.Name,
    (SELECT COUNT(voterfile_voter.ID) 
    FROM voterfile_voter JOIN voterfile_household
    WHERE voterfile_voter.House_ID = voterfile_household.ID
      AND voterfile_household.Precnum = voterfile_precienct.PREC_ID) as Voters
FROM voterfile_precienct JOIN voterfile_county 
ON voterfile_precienct.County_ID = voterfile_County.ID

答案 3 :(得分:3)

请参阅以下示例并相应地修改您的查询。

select COUNT(ResultTPLAlias.id) from 
(select id from Table_name where .... ) ResultTPLAlias;
相关问题