2011-10-22 103 views
0

我的表是這樣的:選擇特定的行

+-------+------+------+------+ 
| index | col1 | col2 | text | 
+-------+------+------+------+ 
| 1 | 1 | 1 | txt1 | 
| 2 | 1 | 2 | txt2 | 
| 3 | 1 | 3 | txt3 | 
+-------+------+------+------+ 
| 4 | 2 | 1 | txt4 | 
| 5 | 2 | 2 | txt5 | 
| 6 | 2 | 3 | txt6 | 
| 7 | 2 | 4 | txt7 | 
| 8 | 2 | 5 | txt8 | 
+-------+------+------+------+ 
| 9 | 3 | 1 | txt9 | 
| 10 | 3 | 2 | txt10| 
| 11 | 3 | 3 | txt11| 
+-------+------+------+------+ 

我需要查詢得到的數據從(COL1 = 1和COL2 = 2)(COL1 = 3和COL2 = 1),像這樣:

+-------+------+------+------+ 
| 2 | 1 | 2 | txt2 | 
| 3 | 1 | 3 | txt3 | 
| 4 | 2 | 1 | txt4 | 
| 5 | 2 | 2 | txt5 | 
| 6 | 2 | 3 | txt6 | 
| 7 | 2 | 4 | txt7 | 
| 8 | 2 | 5 | txt8 | 
| 9 | 3 | 1 | txt9 | 
+-------+------+------+------+ 

有沒有辦法做到以上幾點?

回答

0
SELECT * 
    FROM yourTable 
WHERE `index` between (SELECT min(`index`) FROM yourTable WHERE (col1 = 1 and col2 = 2)) 
        and (SELECT max(`index`) FROM yourTable WHERE (col1 = 3 and col2 = 1)) 
+0

非常感謝,對新的思維方式:) – MAMProgr

0

另一種很好的方法:

select * 
from `yourTable` where 
(
    (col1= 1 AND col2 >= 2) OR 
    (col1= 3 AND col2 <= 1) OR 
    (col1 NOT IN (1, 3)) 
) AND 
col1 BETWEEN 1 AND 3