【问题标题】:Is there any way to do a subselect from a derived table?有没有办法从派生表中进行子选择?
【发布时间】:2013-07-12 01:50:55
【问题描述】:

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

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

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 中是否存在实现相同的概念方式结果。

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

【问题讨论】:

    标签: mysql derived-table sql-subselect


    【解决方案1】:

    您要对查询进行表述的方式是在 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;
    

    【讨论】:

    • 啊哈!关键是能够在没有子选择的情况下使用 case 语句!这正是我不清楚的地方,也是我问题的关键。我可以在 sum 之外使用 case 语句吗?还是需要用某种方法包装? (如果需要方法包装器,我总是可以使用一些无害的 concat 或类似的东西)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 2010-11-22
    • 1970-01-01
    相关资源
    最近更新 更多