K
K
khodos_dmitry2020-02-11 20:37:03
SQL
khodos_dmitry, 2020-02-11 20:37:03

How to make SQL select query on metadata values?

There is a table: save_id, meta_key, meta_value
You need to select save_id, where `meta_key` = 'width_surface' AND `meta_value` = '2.6' and `meta_key` = 'height_surface' AND `meta_value` = '3.53' and there are no more meta fields . I came up with this:

SELECT `save_id` FROM (SELECT `save_id` FROM `cpl_save_meta` WHERE `meta_key` = 'width_surface' AND `meta_value` = '2.6' AND `save_id` IN (SELECT `save_id` FROM `cpl_save_meta` WHERE `meta_key` = 'height_surface' AND `meta_value` = '3.53')) t1 WHERE (SELECT COUNT(*) FROM `cpl_save_meta` WHERE `save_id` = t1.`save_id`) = 2

Is there anything better to eat? Maybe with WordPress requests, who knows.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alexalexes, 2020-02-11
@alexalexes

If save_id is a foreign key (a certain config identifier), then the completeness of the presence of all parameters (both width_surface and height_surface), as well as the absence of other parameters, can be interpreted as follows:

Select t1.save_id, t1.meta_key, t1.meta_value, t2.meta_key as t2_meta_key, t2.meta_value as t2_meta_value
from cpl_save_meta t1
join cpl_save_meta t2 on t1.save_id = t2.save_id
                and t1.meta_key = 'width_surface'  and t1.meta_value = '2.6'
                and t2.meta_key = 'height_surface' and t2.meta_value = '3.53'
where (select count(*) from cpl_save_meta t3
        where t3.save_id = t1.save_id
          and t3.meta_key not in ('width_surface', 'height_surface')) = 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question