首页 文章

MySQL子查询返回多行

提问于
浏览
17

我正在执行此查询:

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 回答

  • 59

    你可以在没有子查询的情况下尝试它,只需一个简单的组:

    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时,任何未分组的列都必须具有聚合子句(f.e. SUM或COUNT . )因此,在这种情况下,您必须对县名,precienct.id和precient.name进行分组 .

  • 13

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

    此查询返回错误:

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

    这是一个很好的查询:

    SELECT * FROM t1 WHERE column1 = ANY (SELECT column1 FROM t2);
    
  • 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

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

    select COUNT(ResultTPLAlias.id) from 
    (select id from Table_name where .... ) ResultTPLAlias;
    

相关问题