MySQL查询限制最大值和最小值

时间:2016-04-01 03:32:58

标签: mysql

我有下表:

    INSERT INTO `test_table` (`id`, `x`, `y`) VALUES (1, 0, 10), (2, 6, 10),
    (3, 9, 10), (4, 2, 9), (5, 4, 9), (6, 3, 8), (7, 7, 8), (8, 9, 8),
    (9, 0, 7), (10, 2, 7), (11, 5, 7), (12, 10, 7), (13, 2, 6), (14, 7, 6),
    (15, 0, 5), (16, 4, 5), (17, 9, 5), (18, 1, 4), (19, 3, 4), (20, 5, 4),
    (21, 10, 4), (22, 8, 3), (23, 3, 2), (24, 6, 2), (25, 2, 1), (26, 8, 1),
    (27, 0, 0), (28, 5, 0), (29, 6, 0), (30, 10, 0);

它代表如下图片:

enter image description here

红色或粉红色单元格中的数字代表" id"并且这些单元格的坐标是" x"和" y"。

我所要做的就是想出一个查询来显示所有单元格(只有红色单元格),不包括灰色方块内的10个单元格。

到目前为止,我有这个:

    SELECT * FROM `test_table` WHERE
    x between 0 and 10 and
    x not between 2 and 8 and
    y between 0 and 10 and
    y not between 2 and 7
    order by id ASC
    LIMIT 30

想象一下,网格在两个方向上都低于0(超出10)(图中没有显示);查询必须有太多限制。无论如何,输出不是我想要的,因为它只给我角落中的细胞(绿色区域内的细胞):1,3,8,27和30

另一种方法是减去此查询:

    SELECT * FROM `test_table` WHERE
    x between 2 and 8 and
    y between 2 and 7
    order by id ASC
    LIMIT 30

来自这个:

    SELECT * FROM `test_table` WHERE
    x between 0 and 10 and
    y between 0 and 10
    order by id ASC
    LIMIT 30

......但又一次;我无法做到:(

2 个答案:

答案 0 :(得分:1)

只需排除x[2:8],y[2,7]

试试这个:

SELECT * FROM `test_table` 
WHERE NOT(x between 2 and 8 AND y between 2 and 7);

答案 1 :(得分:0)

只是添加其他“边”限制;最终的查询是这样实现的:

SELECT * FROM
`test_table` WHERE
x between 0 and 10 and 
y between 0 and 10 and
not
(x between 2 and 8 and
y between 2 and 7)