简体   繁体   中英

How to optimize the inner query mysql

insert into abc(id,item_id,item_type,l_id,c_id)
Select '',o.id,'Open',pl.id,'67' from pls pl, opens o where o.id IN
(select id from Open where not exists (select 1 from ps where type = 'Open' and item_id = opens.id)) and o.type = pl.name;

I have huge data.. Help would be appreciated!!!

Try that:

  insert into abc(id,item_id,item_type,l_id,c_id)
  Select '',o.id,'Open',pl.id,'67' from pls pl
  INNER JOIN opens o ON o.type = pl.name 
  INNER JOIN open ON  o.id = open.id 
  where not exists (select 1 from ps where type = 'Open' and item_id = opens.id)

For the select switching the use of IN to joins:-

SELECT DISTINCT '', o.id, 'Open', pl.id, '67' 
FROM pls pl
INNER JOIN opens o ON and o.type = pl.name
INNER JOIN open op ON and o.id = op.id
LEFT OUTER JOIN ps ON ps.type = 'Open' and ps.item_id = opens.id
WHERE ps.item_id IS NULL

I have added DISTINCT in case the id on the open table is not unique. If it is unique then this can be omitted.

The LEFT OUTER JOIN checks for a matching record on the PS table, and if there is on it is returned. If not the columns from that table are returned as NULL. Then in the WHERE clause the non null ones are omitted from the results.

However for efficiency the indexes on the tables are important. Is there an index on type on the opens table? An index on id on the open table? An index covering type and item_id on the ps table?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM