error : #1242 - Subquery returns more than 1 row

前端 未结 4 621
夕颜
夕颜 2020-12-11 11:39

I got an error: #1242 - Subquery returns more than 1 row when i run this sql.

CREATE VIEW test 
AS 
  SELECT cc_name, 
         COUNT() AS total, 
         (         


        
4条回答
  •  余生分开走
    2020-12-11 11:59

    This is because your subqueries (the SELECT bits that are inside parentheses) are returning multiple rows for each outer row. The problem is with the GROUP BY; if you want to use subqueries for this, then you need to correlate them to the outer query, by specifying that they refer to the same cc_name as the outer query:

    CREATE VIEW test 
    AS 
      SELECT cc_name, 
             COUNT()             AS total, 
             (SELECT COUNT() 
              FROM   bed 
              WHERE  cc_name = bed_outer.cc_name
              AND    respatient_id > 0) AS occupied_beds, 
             (SELECT COUNT(*) 
              FROM   bed 
              WHERE  cc_name = bed_outer.cc_name
              WHERE  respatient_id IS NULL) AS free_beds 
      FROM   bed AS bed_outer
      GROUP  BY cc_name;
    

    (See http://en.wikipedia.org/wiki/Correlated_subquery for information about correlated subqueries.)

    But, as OMG Ponies and a1ex07 say, you don't actually need to use subqueries for this if you don't want to.

提交回复
热议问题