[英]single table parent child relationship query
我編寫了一個查詢來從沒有任何子項目的表中獲取項目。 它工作正常,但速度很慢。 任何更好/更容易/優化的方式來編寫相同的東西?
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 項
下面試試。 還要考慮在PARENT_ITEM_ID
和ITEM_ID
上創建索引
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
我建議not exists
:
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;
出於性能考慮,您需要一個關於order_item(parent_item_id, product_type)
的索引。
注意:我不確定您是否希望在子查詢中使用product_type
過濾器,但這是您的查詢使用的邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.