mysql NOT IN QUERY优化

Gow*_*wri 6 mysql sql query-optimization

我有两个表名为:

  1. table_product
  2. table_user_ownned_auction

table_product

specific_product_id      astatus  ... 
(primary_key,autoinc)
--------------------------------------
1                        APAST    ...
2                        ALIVE    ...
3                        ALIVE    ...
4                        APAST    ... 
5                        APAST    ...
Run Code Online (Sandbox Code Playgroud)

table_user_ownned_auction

own_id     specific_product_id   details   
----------------------------------------
1                  1               XXXX
2                  5               XXXX
Run Code Online (Sandbox Code Playgroud)

我需要选择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 )
Run Code Online (Sandbox Code Playgroud)

......这需要很长时间:

查询花了115.1039秒

...执行.

解释计划

在此输入图像描述

我如何优化它或任何其他方式来选择我想要的?

OMG*_*ies 12

运用 NOT EXISTS

SELECT p.* 
  FROM TABLE_PRODUCT p
 WHERE p.astatus = 'APAST' 
   AND NOT EXISTS (SELECT NULL
                     FROM TABLE_USER_OWNED_AUCTION uoa
                    WHERE uoa.specific_product_id = p.specific_product_id)
Run Code Online (Sandbox Code Playgroud)

运用 LEFT JOIN/IS NULL

   SELECT p.* 
     FROM TABLE_PRODUCT p
LEFT JOIN TABLE_USER_OWNED_AUCTION uoa ON uoa.specific_product_id = p.specific_product_id
    WHERE p.astatus = 'APAST' 
      AND uoa.own_id IS NULL
Run Code Online (Sandbox Code Playgroud)

说明

最佳查询可以通过两个表之间比较的列是否为NULL来确定(IE:如果两个表中的值specific_product_id都可以NULL).

附录

确定最佳查询后,请至少查看创建索引(可能覆盖索引):

  • specific_product_id
  • TABLE_PRODUCT.astatus


The*_*ter 7

尝试在table_user_ownned_auction表上添加索引:

ALTER TABLE table_user_ownned_auction ADD KEY(specific_product_id)
Run Code Online (Sandbox Code Playgroud)

另外,尝试使用non-exists连接:

SELECT p.*
FROM table_product p
    LEFT JOIN table_user_ownned_auction l
      ON p.specific_product_id = l.specific_product_id
WHERE p.astatus = 'APAST' 
    AND l.specific_product_id IS NULL
Run Code Online (Sandbox Code Playgroud)