【问题标题】:Query to return results based on row_count in associated table?根据关联表中的row_count查询返回结果?
【发布时间】:2010-12-09 03:39:18
【问题描述】:

我有两个表:Match 和 MatchShots。

一个match有很多match_shots,match_shots属于match。

在我的匹配表中,我有一个名为 shot_limit 的属性。

我只想根据以下条件返回那些匹配项:

  • 匹配 shot_limit 不为空
  • 匹配 shot_limit = 1 且 match_shots 计数 > 0
  • 匹配 shot_limit = 3 且 match_shots 计数 > 2

【问题讨论】:

    标签: sql mysql join count


    【解决方案1】:

    要查看每个“匹配”如何量化不同的分类,我会将计数添加为结果集中的列。

    select 
          m.matchID, 
          {whatever other columns},
          count(*) MatchCount
       from  
          match m,
          matchShots ms
       where 
              m.matchID = ms.MatchID
          and ( m.shot_Limit = 1 or m.shot_Limit = 3)
       group by
          m.matchID
       having 
          MatchCount >= m.Shot_Limit
    

    【讨论】:

      【解决方案2】:

      怎么样:

      select 
        m.* 
      from 
        match m 
        inner join 
        matchshot ms 
          on ms.id = m.ms_id 
      where 
        m.shot_limit is not null 
      group by 
        m.id 
      having 
        (m.shot_limit = 1 and count(*) > 0) or 
        (m.shot_limit = 3 and count(*) > 2) 
      

      【讨论】:

        猜你喜欢
        • 2021-05-21
        • 1970-01-01
        • 1970-01-01
        • 2013-10-10
        • 2021-12-10
        • 2014-07-13
        • 2011-06-16
        • 2019-08-11
        • 1970-01-01
        相关资源
        最近更新 更多