选择特定行

时间:2011-10-22 10:22:30

标签: mysql sql

我的表是这样的:

+-------+------+------+------+
| 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|
+-------+------+------+------+

我需要查询以获取数据From(col1 = 1和col2 = 2)To(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 |
+-------+------+------+------+

有没有办法做到以上几点?

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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