简体   繁体   English

是否可以在子查询中返回多于一行

[英]Is it possible to return more then one row in sub-query

My Query我的查询

SELECT c.COLUMN_A,
(select count(b.COLUMN_B) from SAME_TABLE_NAME b where COLUMN_B='X' GROUP by   COLUMN_A) as ALIAS_NAME 

FROM SAME_TABLE_NAME c来自 SAME_TABLE_NAME c

Above query throw Error as上面的查询抛出错误为

single-row sub query returns more than one row.单行子查询返回多于一行。

but i need all the row it is returning但我需要它返回的所有行

Try:尝试:

    SELECT COLUMN_A, COUNT(COLUMN_B)  AS ALIAS_NAME 
      FROM SAME_TABLE_NAME 
      WHERE COLUMN_B='X' GROUP BY COLUMN_A

If that's not right, please post your real schema and an example of your data.如果这不对,请发布您的真实架构和数据示例。

you are getting multiple results in your column.你在你的列中得到多个结果。 your looking for something like this.你正在寻找这样的东西。

select  COLUMN_A, count(b.COLUMN_B) from SAME_TABLE_NAME b 
            where COLUMN_B='X' GROUP by COLUMN_A

You may try this.你可以试试这个。

SELECT c.COLUMN_A,
(select count(b.COLUMN_B) from SAME_TABLE_NAME b 
 where COLUMN_B='X' 
 AND C.COLUMN_A=B.COLUMN_A   --- THIS WHERE CLAUSE IS ADDED TO MAP ALL YOUR COUNT RECORD WITH ITS RESPECTED COLUMN
 GROUP by B.COLUMN_A) as ALIAS_NAME 
FROM SAME_TABLE_NAME c

A scalar subquery should return at most one row.标量子查询最多应返回一行。 Hence, GROUP BY is not appropriate.因此, GROUP BY恰当的。 If you want to express this using a subquery, you want a correlated subquery without GROUP BY :如果您想使用子查询来表达这一点,您需要一个没有GROUP BY的相关子查询:

SELECT c.COLUMN_A,
       (SELECT count(b.COLUMN_B) 
        FROM SAME_TABLE_NAME b 
        WHERE c.COLUMN_A = b.COLUMN_A AND
              b.COLUMN_B = 'X' 
       ) as ALIAS_NAME 
FROM SAME_TABLE_NAME c;

However, the better approach is to use window functions, available in the more recent versions of MySQL:然而,更好的方法是使用窗口函数,在更新的 MySQL 版本中可用:

SELECT c.COLUMN_A,
       SUM(c.COLUMN_B = 'X') OVER (PARTITION BY c.COLUMN_A) as ALIAS_NAME 
FROM SAME_TABLE_NAME c;

Note that you should qualify all column references.请注意,您应该限定所有列引用。 This is especially true with subqueries, where the scoping rules may sometimes not do what you intend.对于子查询尤其如此,其中的范围规则有时可能不会按照您的意图执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM