Gow*_*wri 6 mysql sql query-optimization
我有两个表名为:
specific_product_id astatus ...
(primary_key,autoinc)
--------------------------------------
1 APAST ...
2 ALIVE ...
3 ALIVE ...
4 APAST ...
5 APAST ...
Run Code Online (Sandbox Code Playgroud)
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 EXISTSSELECT 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_idTABLE_PRODUCT.astatus尝试在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)
| 归档时间: |
|
| 查看次数: |
5612 次 |
| 最近记录: |