2011-10-22 65 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