Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding a common ID (value) in a normalized table based on several where clauses

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

You could use conditional aggregation to avoid self-joins.


select offer_id
from (
  select offer_id, 
    sum(case when pkey = 'shoesize' and pvalue = 'size_48' then 1 else 0 end) cond1, 
    sum(case when pkey = 'sport' and pvalue = 'running' then 1 else 0 end) cond2
  from offer_properties
  group by offer_id
  )z
where cond1> 0 and cond2> 0;
offer_id
12

View on DB Fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading