gpt4 book ai didi

sql - 重写这个子查询?

转载 作者:行者123 更新时间:2023-11-29 01:00:08 25 4
gpt4 key购买 nike

我正在尝试构建一个新表,以便现有表中的值不包含在另一个表中(但显然以下检查是否包含)。以下是我的表结构:

mysql> explain t1;
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| point | bigint(20) unsigned | NO | MUL | 0 | |
+-----------+---------------------+------+-----+---------+-------+

mysql> explain whitelist;
+-------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| x | bigint(20) unsigned | YES | | NULL | |
| y | bigint(20) unsigned | YES | | NULL | |
| geonetwork | linestring | NO | MUL | NULL | |
+-------------+---------------------+------+-----+---------+----------------+

我的查询是这样的:

SELECT point 
FROM t1
WHERE EXISTS(SELECT source
FROM whitelist
WHERE MBRContains(geonetwork, GeomFromText(CONCAT('POINT(', t1.point, ' 0)'))));

解释:

    +----+--------------------+--------------------+-------+-------------------+-----------+---------+------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+--------------------+-------+-------------------+-----------+---------+------+------+--------------------------+
| 1 | PRIMARY | t1 | index | NULL | point | 8 | NULL | 1001 | Using where; Using index |
| 2 | DEPENDENT SUBQUERY | whitelist | ALL | _geonetwork | NULL | NULL | NULL | 3257 | Using where |
+----+--------------------+--------------------+-------+-------------------+-----------+---------+------+------+--------------------------+

查询在 t1 中执行 1000 条记录需要 6 秒,这对我来说是 Not Acceptable 。如果我没有要加入的列,我如何使用加入(或者可能是更快的方法,如果存在的话)重写这个查询?我想在最坏的情况下,即使是存储过程也是可以接受的。我的目标是最终创建一个包含来自 t1 的条目的新表。有什么建议吗?

最佳答案

除非查询优化器失败,否则 WHERE EXISTS 结构应该产生与带有 GROUP 子句的连接相同的计划。查看优化 MBRContains(geonetwork, GeomFromText(CONCAT('POINT(', t1.point, '0)')))),这可能是您的查询花费所有时间的地方。我对此没有建议,但这是使用 JOIN 编写的查询:

Select t1.point
from t1
join whitelist on MBRContains(whitelist.geonetwork, GeomFromText(CONCAT('POINT(', t1.point, ' 0)'))))
group by t1.point
;

或者获取t1中不在白名单中的点数:

Select t1.point
from t1
left join whitelist on MBRContains(whitelist.geonetwork, GeomFromText(CONCAT('POINT(', t1.point, ' 0)'))))
where whitelist.id is null
;

关于sql - 重写这个子查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3859304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com