Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在MySql中返回具有相同列值的行 让我们考虑下表-< /P> ID Score 1 95 2 100 3 88 4 100 5 73_Mysql_Sql - Fatal编程技术网

如何在MySql中返回具有相同列值的行 让我们考虑下表-< /P> ID Score 1 95 2 100 3 88 4 100 5 73

如何在MySql中返回具有相同列值的行 让我们考虑下表-< /P> ID Score 1 95 2 100 3 88 4 100 5 73,mysql,sql,Mysql,Sql,我是一个彻头彻尾的SQLNoob,但是我如何返回IDS2和ID4的分数呢? 因此,它应该返回100,因为它在ID2和ID4中都有特性。这是一个“集合中的集合”查询的示例。我建议使用have子句进行聚合,因为这是最灵活的方法 select score from t group by score having sum(id = 2) > 0 and -- has id = 2 sum(id = 4) > 0 -- has id = 4 这是通过分数进行聚合。然后,

我是一个彻头彻尾的SQLNoob,但是我如何返回IDS2和ID4的分数呢? 因此,它应该返回100,因为它在ID2和ID4中都有特性。这是一个“集合中的集合”查询的示例。我建议使用
have
子句进行聚合,因为这是最灵活的方法

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”的分数

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(*)
。这是真的,但根据我的经验,几乎所有这种模式的使用都涉及到唯一的列。
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)
    )