2010-11-03 43 views
2

test與列compname version和表Bugsbugid compname以下輸出的SQL查詢?

數據列test

A 1.2
B 1.5
C 1.6
B 1.3
C 1.5
A 1.6
B 1.6

數據爲Bugs

1 A
1 C
2 A
2 B
3 A
3 B
3 C

查詢:

Output the compname where version=1.6 and affected by bugid=1 along with the first(min) version in which the component appeared

輸出:
A 1.2
C 1.5

我使用這個查詢,但可以在此進行得更快:

select compname,min(version) from test where compname IN (select compname from test where version='1.6' and compname IN (select compname from Bugs where bugid=1)) group by compname

回答

5

聯接速度更快,並且您需要額外的自聯接來獲取最小版本。

SELECT t.compname, min(t2.version) 
FROM test t 
INNER JOIN Bugs b 
    ON t.compname = b.compname 
INNER JOIN test t2 
    ON t.compname = t2.compname 
WHERE bugid = 1 AND t.version='1.6' 
GROUP BY t.compname 

(在我的測試給你列出了相同的結果)

+0

爲什麼第二次加入? – 2010-11-03 19:58:28

+1

否則,你只會得到所檢索行的最小值,這些值只是匹配'bugid = 1 AND t.version ='1.6''的值。這樣你可以獲得所有可能的版本,並選擇該集合的最小值。 – theazureshadow 2010-11-03 20:00:42

+0

+1,很好。 – 2010-11-03 20:02:19

0

您可以使用INNER JOIN:

SELECT test.compname, min(test.version) 
FROM test INNER JOIN Bugs 
ON test.compname = Bugs.compname 
WHERE test.version = '1.6' AND Bugs.bugid =1 
GROUP BY test.compname 
+0

是如何從@Jason或我的答案,這有什麼不同? – 2010-11-03 19:59:03

+1

@Abe - 沒有別名,他顛倒了'WHERE'子句的順序:) – JNK 2010-11-03 20:03:02

+0

@Abe - 我發佈後我只看到了這些答案...顯然我是一個更慢的typer,然後你:) – duduamar 2010-11-03 20:26:13