Mysql 单表父子关系查询

Mysql 单表父子关系查询,mysql,sql,Mysql,Sql,我编写了一个查询,从没有任何子项的表中获取项。工作正常,但速度很慢。 有没有更好/更容易/优化的方法来编写相同的内容 select distinct id, (select count(i.item_id) from order_item as i where i.parent_item_id = o.item_id) as c from order_item as o where product_type = 'bundle' having c = 0 order by id desc lim

我编写了一个查询,从没有任何子项的表中获取项。工作正常,但速度很慢。 有没有更好/更容易/优化的方法来编写相同的内容

select distinct id, (select count(i.item_id) from order_item as i where i.parent_item_id = o.item_id) as c
from order_item as o
where product_type = 'bundle'
having c = 0
order by id desc
limit 10;
这些字段中很少有用于获得结构概念的字段

Table: order_item
Columns:
item_id PK
order_id
parent_item_id
product_id
product_type


item_id  | order_id | parent_item_id | product_id | product_type
-----------------------------------------------------------------
   1     |    1     |     null       |     1      |   bundle
   2     |    1     |       1        |     2      |   simple
   3     |    1     |       1        |     3      |   simple
   4     |    1     |     null       |     4      |   bundle
   5     |    2     |     null       |     1      |   bundle
   6     |    2     |       5        |     2      |   simple
   7     |    2     |       5        |     3      |   simple 

查询应该只返回第4个项目

我建议
不存在

select oi.*
from order_item oi
where oi.product_type = 'bundle' and
      not exists (select 1
                  from order_item oi2
                  where oi2.parent_item_id = oi.item_id and oi2.product_type = 'bundle'
                 )
order by id desc
limit 10;
为了提高性能,您需要在
订单项目(父项项目id、产品类型)上建立索引


注意:我不确定您是否希望子查询中的
产品类型
过滤器,但这是您的查询所使用的逻辑。

请尝试下面的内容。还考虑在<代码> PARTRONITIMSIDID<代码>和<代码> ITEMIDID<代码>

上创建索引。
SELECT OI.*
  FROM ORDER_ITEM OI
       LEFT JOIN ORDER_ITEM OI2
          ON OI2.PARENT_ITEM_ID = OI.ITEM_ID
 WHERE OI.PRODUCT_TYPE = 'bundle' AND OI2.PARENT_ITEM_ID IS NULL

请提供样本数据和所需结果,以解释“子项”的含义。@GordonLinoff问题已更新。请查看更改内部查询产品类型条件后返回的结果是否正确。我已经编辑了答案,但是,表演几乎没有difference@AhmedJaved . . . 你有推荐的索引吗?没有,但是ismetguzelgun的查询在没有添加新索引的情况下运行得足够快。实际上,该表是一个生产站点表,大小约为6GB。所以不能做任何改变