Mysql
 SQL >> Datenbank >  >> RDS >> Mysql

Mehrere GROUP_CONCAT-Joins mit WHERE statt HAVING optimieren

Die wichtigste Optimierung ist, WHERE statt HAVING zu verwenden. WHERE wird beim Suchen der Zeilen angewendet und kann Indizes nutzen. HAVING läuft nach der Zeilenauswahl und kann per Design keine Indizes verwenden.

SELECT
  p.id,
  p.name,
  p.default_image_id,
  GROUP_CONCAT(DISTINCT pc.colour_id) AS product_colours,
  GROUP_CONCAT(DISTINCT pt.tag_id) AS product_tags,
  GROUP_CONCAT(DISTINCT ps.tag_id) AS product_sizes
FROM shop_products p
JOIN shop_product_to_colours pc_test
  ON p.id = pc_test.product_id AND pc_test.colour_id = 18
JOIN shop_products_to_tag pt_test
  ON p.id = pt_test.product_id AND pt_test.tag_id = 1
JOIN shop_product_colour_to_sizes ps_test
  ON p.id = ps_test.product_id AND ps_test.tag_id = 17
JOIN shop_product_to_colours pc ON p.id = pc.product_id
JOIN shop_products_to_tag pt ON p.id = pt.product_id
JOIN shop_product_colour_to_sizes ps ON p.id = ps.product_id
WHERE p.category_id = '50'
GROUP BY p.id
ORDER BY p.name ASC;

Update

Wir joinen jede Tabelle zweimal. Der erste Join prüft, ob der geforderte Wert enthalten ist, der zweite liefert die Daten für GROUP_CONCAT.

Update 2

Wenn Sie die GROUP_CONCAT-Listen nicht brauchen, wird die Abfrage deutlich einfacher:

SELECT p.id, p.name, p.default_image_id
FROM shop_products p
JOIN shop_product_to_colours pc ON p.id = pc.product_id
JOIN shop_products_to_tag pt ON p.id = pt.product_id
JOIN shop_product_colour_to_sizes ps ON p.id = ps.product_id
WHERE p.category_id = '50'
  AND pc.colour_id = 18
  AND pt.tag_id = 1
  AND ps.tag_id = 17
GROUP BY p.id
ORDER BY p.name ASC;