如何优化内部查询mysql

时间:2014-07-07 08:30:22

标签: mysql ruby-on-rails

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;

我有大量数据.. 帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

试试:

  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)

答案 1 :(得分:0)

对于选择切换使用IN加入: -

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

我已经添加了DISTINCT,以防open table上的id不唯一。如果它是唯一的,那么这可以省略。

LEFT OUTER JOIN检查PS表上的匹配记录,如果有,则返回。如果不是,则该表中的列将返回为NULL。然后在WHERE子句中,结果中省略了非null值。

然而,为了提高效率,表格上的索引很重要。打开表上是否有类型索引?打开表上的id索引? ps表上覆盖type和item_id的索引?