[英]MySQL table self-join returns too many rows
因此,我有一個表my_table
,具有主鍵, id
( INT
)和其他列foo
( VARCHAR
)和bar
( DOUBLE
)。 每個foo
應該在表中出現一次,並帶有一個關聯的bar
值,但是我知道我有幾行具有相同的foo
關聯了不同的bar
。 如何獲得包含相同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的行數?
要回答您的最新問題:
在SQL中,有沒有一種方法可以為每個foo計數具有該foo的行數,但小數點相差超過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;
例如,如果您有5行foo='A'
和10行foo='B'
則自我聯接會將每個A行與每個A行(包括自身)以及每個B行與彼此的B行,所以很簡單
SELECT t1.id, t1.bar, t2.id, t2.bar, t1.foo
FROM my_table t1, my_table t2
WHERE t1.foo=t2.foo
將返回5*5+10*10=125
行。 過濾值將減少該數字,但與開始時相比,您可能仍然擁有(明顯)更多的行。 例如,如果我們假設B行的bar
值分別為5到50,那意味着它們將與以下項匹配:
bar = 5 - 0 rows that have bar less than -5
bar = 10 - 0 rows that have bar less than 0
bar = 15 - 0 rows that have bar less than 5
bar = 20 - 1 rows that have bar less than 10
bar = 25 - 2 rows that have bar less than 15
bar = 30 - 3 rows that have bar less than 20
bar = 35 - 4 rows that have bar less than 25
bar = 40 - 5 rows that have bar less than 30
bar = 45 - 6 rows that have bar less than 35
bar = 50 - 7 rows that have bar less than 40
因此,僅B行就有28個結果,並且該數目隨具有foo
值相同的行的平方而增加。
您是否嘗試過使用“新” JOIN
語法進行相同的操作?
SELECT t1.*,
t2.*
FROM my_table t1
JOIN my_table t2 ON t1.foo = t2.foo
WHERE (t1.bar - t2.bar) > 10
我不認為這可以解決您的問題,但是對我而言,至少這是我的起點。
我也可以嘗試這樣:
SELECT t1.*,
t2.*
FROM my_table t1
JOIN my_table t2 ON t1.foo = t2.foo AND t1.id != t2.id
WHERE (t1.bar - t2.bar) > 10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.