mysql - 有什么方法可以从派生表中进行子选择吗?

标签 mysql derived-table subquery

我遇到一种情况,我正在构建一个派生数据透视表,然后我希望能够根据各种条件对其进行子选择(实际上是制作一个数据透视表)。

所以......在伪中它看起来像这样......

select
   (select sum(score) from derivedTable where username like 'a%') as scoresForANames,
   (select sum(score) from derivedTable where username like 'b%') as scoresForBNames

from
  ( select username, score from gameTable where gameId = 111) derivedTable

请注意,这是一个荒谬的简化示例,用于说明我所追求的内容...我根本不需要解决这个示例...我只需要了解 mySQL 中是否有一种概念方法可以实现相同的目的结果。

问题是 衍生表 对于外部选择中的子选择不可见。所以,我很好奇如何才能达到相同的结果,或者我是否不得不编写单独考虑所有标准的子选择。

最佳答案

您想要表达查询的方式是在 select 子句中根本没有子查询:

select sum(case when username like 'a%' then score end) as scoresForANames,
       sum(case when username like 'b%' then score end) as scoresForBNames
from (select username, score
      from gameTable
      where gameId = 111
     ) derivedTable;

当然,在这种情况下,您根本不需要派生表:

select sum(case when username like 'a%' then score end) as scoresForANames,
       sum(case when username like 'b%' then score end) as scoresForBNames
from gameTable gt
where gameId = 111;

关于mysql - 有什么方法可以从派生表中进行子选择吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17633225/

相关文章:

mysql - SQL 递归引用完整性

mysql - 咨询子查询和正则表达式的使用

MySQL 连接优化 : Improving join type with derived tables and GROUP BY

sql - 子查询是重用变量的唯一选择吗?

mysql - order by 和 group by 两者都在时间不工作

mysql - 使用不同的行值通过一个查询更新多行

mysql - SQL如何计算每月有x笔交易的信用卡数量

mysql - mysql派生表如何使用索引

mysql - 比较MySQL同一列的计数以获得百分比

mysql - 如何在 SELECT 语句中为非特定键选择 GROUPED BY 平均值