【问题标题】:How to return rows that have the same column values in MySql如何在MySql中返回具有相同列值的行
【发布时间】:2013-05-18 05:51:27
【问题描述】:

让我们考虑下表-

ID Score
1  95

2  100

3  88

4  100

5  73

我是一个 SQL 新手,但如何返回包含 ID 2 和 4 的分数? 所以它应该返回 100,因为它在 ID 2 和 4 中都有特色

【问题讨论】:

    标签: mysql sql relational-division


    【解决方案1】:

    这是“sets-within-sets”查询的示例。我建议使用 having 子句进行聚合,因为它是最灵活的方法。

    select score
    from t
    group by score
    having sum(id = 2) > 0 and -- has id = 2
           sum(id = 4) > 0     -- has id = 4
    

    这样做是按分数聚合。然后having 子句(sum(id = 2))的第一部分计算每个分数有多少个“2”。第二个是计算有多少个“4”。仅返回“2”和“4”的分数。

    【讨论】:

      【解决方案2】:
      SELECT score
      FROM t
      WHERE id in (2, 4)
      HAVING COUNT(*) = 2 /* replace this with the number of IDs */
      

      这将选择 ID 为 2 和 4 的行。HAVING 子句然后确保我们找到了这两行;如果缺少任何一个,则计数将小于 2。

      这假定id 是一个唯一的列。

      【讨论】:

      • 在更一般的情况下,当 id 不能保证唯一时,我们可以使用 COUNT(DISTINCT id) 代替 COUNT(*) b>.
      • 确实如此,但根据我的经验,这种模式的几乎所有使用都涉及独特的列。
      【解决方案3】:
      select Score
      from tbl a
      where a.ID = 2 -- based off Score with ID = 2
          --include Score only if it exists with ID 6 also
          and exists (
              select 1
              from tbl b
              where b.Score = a.Score and b.ID = 6
          )
          -- optional?  ignore Score that exists with other ids as well
          and not exists (
              select 1
              from tbl c
              where c.Score = a.Score and c.ID not in (2, 6)
          )
      

      【讨论】:

        猜你喜欢
        • 2021-01-01
        • 1970-01-01
        • 2015-11-14
        • 1970-01-01
        相关资源
        最近更新 更多