mysql NOT IN QUERY 优化
我有两个表,名称为:
- table_product
- table_user_ownned_auction
table_product
specific_product_id astatus ...
(primary_key,autoinc)
--------------------------------------
1 APAST ...
2 ALIVE ...
3 ALIVE ...
4 APAST ...
5 APAST ...
table_user_ownned_auction
own_id specific_product_id details
----------------------------------------
1 1 XXXX
2 5 XXXX
我需要选择 atatus = APAST
,而不是在表 2 中。
这意味着,在上面的结构中,table1 有 3 个 APAST 状态(1、4、5)。但在表 2 Specific_product_id (1,5) 中仅存储,因此我需要选择 Specific_product_id = 4
我使用了此查询
SELECT *
FROM table_product
WHERE astatus = 'APAST'
AND specific_product_id NOT IN (SELECT specific_product_id
FROM table_user_ownned_auction )
...这需要这么长时间:
查询花费了 115.1039 秒
执行耗时 115.1039 秒。
解释计划
我如何优化它或以其他方式选择我想要的内容?
I have two tables named as:
- table_product
- table_user_ownned_auction
table_product
specific_product_id astatus ...
(primary_key,autoinc)
--------------------------------------
1 APAST ...
2 ALIVE ...
3 ALIVE ...
4 APAST ...
5 APAST ...
table_user_ownned_auction
own_id specific_product_id details
----------------------------------------
1 1 XXXX
2 5 XXXX
I need to select atatus = APAST
, and not in table 2.
Which means, in above structure table1 has 3 APAST status (1,4,5). But in table 2 specific_product_id (1,5) only stored so i need to select specific_product_id = 4
I used this query
SELECT *
FROM table_product
WHERE astatus = 'APAST'
AND specific_product_id NOT IN (SELECT specific_product_id
FROM table_user_ownned_auction )
...which takes this long:
Query took 115.1039 sec
...to execute.
EXPLAIN PLAN
How can i optimize it or any other way to select what i want?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试在
table_user_ownned_auction
表上添加索引:另外,尝试使用
non-exists
连接:Try adding a index on the
table_user_ownned_auction
table:Also, try using a
non-exists
join:使用
NOT EXISTS
使用
LEFT JOIN/IS NULL
说明
最佳查询可以通过两个表之间比较的列是否可为 NULL 来确定(即:如果 <任一表中的 code>specific_product_id 都可以为
NULL
)。NOT IN
或NOT EXISTS
是 MySQL 中的最佳选择附录
一旦确定了最佳查询,请查看创建索引(可能覆盖索引) 至少:
special_product_id
TABLE_PRODUCT.status
Using
NOT EXISTS
Using
LEFT JOIN/IS NULL
Explanation
The most optimal query can be determined by if the columns compared between the two tables are NULLable (IE: if the values of
specific_product_id
in either table can beNULL
).NOT IN
orNOT EXISTS
is the best choice in MySQLAddendum
Once the optimal query has been determined, take a look at creating indexes (possibly covering indexes) for at least:
specific_product_id
TABLE_PRODUCT.astatus