私は MySQL で派生クエリを使用するのが初めてで、2 つの点で問題があります。
1) t1.dCount を参照して、各 optionId の xcart_images_D.productId の数をカウントするにはどうすればよいですか?
2) このクエリの派生 SELECT を合理化するにはどうすればよいですか? (現在、このクエリの実行には 45 秒かかります)
SELECT xp.productid, xp.product, xc.classid, xco.optionid, xco.option_name, xiW.id, xiW.image_path, t1.dCount
FROM xcart_products xp
INNER JOIN xcart_variants xv ON xp.productid = xv.productid
INNER JOIN xcart_variant_items xvi ON xv.variantid = xvi.variantid
INNER JOIN xcart_class_options xco ON xvi.optionid = xco.optionid
INNER JOIN xcart_classes xc ON xco.classid = xc.classid AND xc.class = 'COLOR'
LEFT JOIN xcart_images_W xiW ON xiW.id = xvi.variantid
LEFT JOIN (
SELECT COUNT(xiD.optionid) as dCount
FROM xcart_products xp2
INNER JOIN xcart_classes xc2 ON xp2.productid = xc2.productid AND xc2.class = 'Color'
INNER JOIN xcart_class_options xco2 ON xc2.classid = xco2.classid
LEFT JOIN xcart_images_D xiD ON xiD.optionid = xco2.optionid
) as t1 ON xiW.id = xvi.variantid
GROUP BY xco.optionid
ORDER by xp.product DESC
これはカウントの作業バージョンですが、派生した選択はありません-
SELECT xp.productid, xp.product, xc.classid, xco.optionid, xco.option_name, xiD.image_path, xiD.path_on_server, count(xiD.optionid) as cnt
FROM xcart_products xp
INNER JOIN xcart_classes xc ON xp.productid = xc.productid AND xc.class = 'Color'
INNER JOIN xcart_class_options xco ON xc.classid = xco.classid
LEFT JOIN xcart_images_D xiD ON xiD.optionid = xco.optionid
GROUP BY xp.product, xco.optionid
ORDER by xp.product DESC
必要な場合は、ここに DB レイアウトを示します -
+ xcart_products
- productid*
- product
+ xcart_variants
- variantid*
- productid (xcart_products.productid)
+ xcart_variant_items [bridge table]
- optionid*
- variantid (xcart_variants.variantid)
+ xcart_classes
- classid*
- productid (xcart_products.productid)
- class
+ xcart_class_options
- optionid*
- option_name
- classid (xcart_classes.classid)
+ xcart_images_W
- imageid*
- id (xcart_variants.variantid)
- image_path
+ xcart_images_D
- imageid* [not relational with xcart_images_W.imageid]
- id (xcart_products.productid)
- optionid (xcart_class_options.optionid)
* Primary Key
() relational data
[] notes