SQL检查表中的值是否在另一个表的2列范围内

时间:2019-05-29 15:05:55

标签: mysql sql

我正在尝试检查TABLE_1中的值是否在基于TABLE_2中2列的范围内。我可以根据问题SQL: Checking if a number within range of multiple ranges中提供的答案来完成操作,但是当我将此方法与大型数据集(两个表中的〜40K行)一起使用时,它使SQL Server上的CPU耗尽,查询占用了过多资源3分钟。有没有一种方法可以优化此查询并限制该查询使用的CPU?如果没有,是否存在一个可能更有效的替代查询。

TABLE_1:

mysql> SELECT * FROM TABLE_1;
+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  1 | Apples  |  2314 |
|  2 | Oranges |  3412 |
|  3 | Oranges |  1296 |
|  4 | Apples  |  2230 |
|  5 | Apples  |  5293 |
|  6 | Oranges |  1994 |
+----+---------+-------+
6 rows in set (0.00 sec)

TABLE_2:

mysql> SELECT * FROM TABLE_2;
+----+---------+-------------+-----------+
| ID | FRUIT   | START_RANGE | END_RANGE |
+----+---------+-------------+-----------+
|  1 | Apples  |        2300 |      2400 |
|  2 | Apples  |        7000 |      8000 |
|  3 | Oranges |        1296 |      1296 |
|  4 | Apples  |        5000 |      6000 |
|  5 | Oranges |        9000 |      9999 |
|  6 | Oranges |        8000 |      9000 |
+----+---------+-------------+-----------+

查询:

SELECT *
FROM TABLE_1
WHERE NOT EXISTS (SELECT 1 FROM TABLE_2
                  WHERE TABLE_1.FRUIT = TABLE_2.FRUIT 
                  AND TABLE_1.COUNT BETWEEN TABLE_2.START_RANGE AND TABLE_2.END_RANGE);

输出:

+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  2 | Oranges |  3412 |
|  4 | Apples  |  2230 |
|  6 | Oranges |  1994 |
+----+---------+-------+
3 rows in set (0.00 sec)

3 个答案:

答案 0 :(得分:0)

这是您的查询:

const c = new Cell(null!);
c.status.otherFunctionalityThatChangesDependingOnStatus(); // It's good to be alive!
c.toggleCell();
c.status.otherFunctionalityThatChangesDependingOnStatus(); // I'm out of here!
c.toggleCell();
c.status.otherFunctionalityThatChangesDependingOnStatus(); // It's good to be alive!

为了提高性能,请从SELECT * FROM TABLE_1 WHERE NOT EXISTS (SELECT 1 FROM TABLE_2 WHERE TABLE_1.FRUIT = TABLE_2.FRUIT AND TABLE_1.COUNT BETWEEN TABLE_2.START_RANGE AND TABLE_2.END_RANGE); 上的索引开始。

答案 1 :(得分:0)

not exists可能是性能最好的版本,但是您可以尝试等效的left join

select table1.*
from Table1
left join table2
on table1.fruit = table2.fruit
and table1.count between table2.start_range and table2.end_range
where table2.id is null

答案 2 :(得分:0)

除了在table_2.fruit上添加索引(如@Gordon所建议的那样),您还可以尝试以下操作:

SELECT *
FROM   table_1
WHERE  id NOT IN (SELECT tab1.id
                  FROM   table_1 tab1
                  JOIN   table_2 tab2
                    ON   tab1.fruit = tab2.fruit
                   AND   tab1.count BETWEEN tab2.start_range AND tab2.end_range);

这当然假设ID是主键。