2010-04-07 14 views
0
檢索數據的序列

比方說,我有一個包含下列數據的表:不同列

| id | t0 | t1 | t2 | 
______________________ 
| 1 | 4 | 5 | 6 | 
| 2 | 3 | 5 | 2 | 
| 3 | 6 | 4 | 5 | 
| 4 | 4 | 5 | 9 | 
| 5 | 14 | 5 | 49 | 

我想檢索包含所有行4,5,6(無論該表中的數字的位置) ,因此第1行的&行將被選中。如何用SQL查詢做到這一點?

該表包含數千條記錄。

回答

7

你可以這樣說:

select * 
from table 
where 4 in (t0, t1, t2) 
    and 5 in (t0, t1, t2) 
    and 6 in (t0, t1, t2) 
0

你總是可以做到這一點 「硬」 的方式:

select * 
    from tbl 
where (t0 = 4 AND t1 = 5 AND t2 = 6) 
    or (t0 = 5 AND t1 = 6 AND t2 = 4) 
    or (t0 = 6 AND t1 = 4 AND t2 = 5) 
0

另一種 「硬」 的方式:

DECLARE @table TABLE (id int, t0 int, t1 int, t2 int) 

INSERT INTO @table(id, t0, t1, t2) VALUES(1, 4, 5, 6) 
INSERT INTO @table(id, t0, t1, t2) VALUES(2, 3, 3, 2) 
INSERT INTO @table(id, t0, t1, t2) VALUES(3, 6, 4, 5) 
INSERT INTO @table(id, t0, t1, t2) VALUES(4, 4, 5, 5) 

SELECT * 
FROM @table 
WHERE (t0+t1+t2) = 15 
    AND t0 BETWEEN 4 AND 6 
    AND t1 BETWEEN 4 AND 6 
    AND t2 BETWEEN 4 AND 6 
    AND t0 <> t1 
+2

5+ 5 + 5也使得15 :) – Mercurybullet 2010-04-07 00:28:00

+0

+1 @Mercurybullet。需要t0 <> t1(等)檢查WoLpH的解決方案。將解決。 – Dane 2010-04-07 20:40:00