2010-11-03 27 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