Ich habe ein kleines Shop-System und möchte jetzt ein Produkt mit bestimmten Attributen und Bedingungen auswählen.Suche nach Produkten nach bestimmten Attributen
Hier ist mein Setup:
Tabelle XYZ:
- product_id
- attribute_id
- attribute_group_id
So, jetzt ich alle Produkte auswählen möchten, die die Attribut-IDs hat 1,3,5 und 7, aber nicht 9 und 2.
Wie kann ich dies auf eine einfache Art und Weise tun, war meine erste Idee, es nach Produkt-ID und group_concat die Attribut-IDs zu gruppieren und "mit" zu verwenden, um die gewünschten Attribut-IDs ein- und auszuschließen.
SELECT CONCAT('_',GROUP_CONCAT(attribute_id SEPARATOR '_'),'_') as attrs,
product_id
FROM my_table
GROUP BY product_id
HAVING (attrs LIKE '%_1_%'
AND attrs LIKE '%_3_%'
AND attrs LIKE '%_5_%'
AND attrs LIKE '%_7_%')
AND (attrs NOT LIKE '%_2_%'
AND attrs NOT LIKE '%_9_%')
Das funktioniert, aber es gibt eine bessere Lösung, oder?
Das Problem ist, dass ich das Produkt, das alle diese attrs hat, will Ihre Abfrage wird mir jedes Produkt, das eine dieser attrs hat. – marco