I have the following table (offer_properties) in MYSQL for an e-commerce website:
+----------+-------------+---------+
| offer_id | pkey | pvalue |
+----------+-------------+---------+
| 63 | shoesize | shoe_47 |
| 63 | sport | walking |
| 63 | color | multi |
| 12 | color | multi |
| 12 | shoesize | size_48 |
| 12 | shoesize | size_47 |
| 12 | shoesize | size_46 |
| 12 | sneakertype | comfort |
| 12 | sport | running |
+----------+-------------+---------+
What is the easiest way to find the offers where
shoesize = size_48 AND sport = running
I could do it by
select offer_id from offer_properties where (pkey = "sport" and pvalue = "running") and offer_id IN (select offer_id from offer_properties where (pkey = "shoesize" and pvalue = "size_48"));
However, this recursive approach makes it really difficult as there could be various property match requests. Moreover, I have other tables that I need to JOIN and the queries gets complicated quite quickly. I have one table that holds the values (price, description, etc.) and another normalized table that holds offer tags.
I LEFT JOIN
to find the offers that matches certain tags with certain properties and with certain values. However, things get quite complicated very quikly.
What would be your guidance for such scenarios? Should I use simple queries with Promises and use the app logic to filter things step by step?
Many thanks
3
Answers
You can use quite simple self join:
Or you could use
EXIST
. It quite similar to your current query.Both solutions require additional constructions, but with current model, I believe you have no chance avoiding it.
On the other hand, I would argue that exists (as your current query) could be written in a single line, and should not clutter your query to much.
You could use
conditional aggregation
to avoid self-joins.View on DB Fiddle
No need for joins, nor for subqueries. We can do direct filtering on aggregates with a
having
clause: