所以我有一个表,my_table
,有一个主键,id
(INT
),还有更多列 foo
(VARCHAR
) 和 bar
(DOUBLE
)。每个 foo
都应该在我的表中出现一次,并带有一个关联的 bar
值,但我知道我有几行具有相同的 foo
关联不同栏
。如何获取包含相同 foo
值但具有不同 bar
(例如,相差超过 10 个)的那些行的列表?
我试过:
SELECT t1.id, t1.bar, t2.id, t2.bar, t1.foo FROM my_table t1, my_table t2 WHERE t1.foo=t2.foo AND t1.bar - t2.bar > 10.;
但是我得到了很多很多的结果(超过 my_table
中的总行数)。我觉得我一定在做一些非常愚蠢的事情,但看不出我的错误。
啊 - 谢谢 SWeko:我想我明白为什么我会得到这么多结果了。 SQL 中是否有一种方法可以计算每个 foo
具有该 foo
但 bar
相差超过 10 的行数。 ?
最佳答案
回答您最近的问题:
Is there a way in SQL of counting, for each foo, the number of rows with that foo but bars differing by more than 10.?
这样的查询应该有效:
select t1.id, t1.foo, t1.bar, count(t2.id) as dupes
from my_table t1
left outer join my_table t2 on t1.foo=t2.foo and (t1.bar - t2.bar) > 10
group by t1.id, t1.foo, t1.bar;
关于MySQL 表自连接返回太多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15027744/