S
S
Sergey2014-07-11 16:22:26
MySQL
Sergey, 2014-07-11 16:22:26

How to simplify sql query?

Hello, there is a table with characteristic values ​​in this form:
id_page-----id_field-----value
1-------------11----------- 100
1-------------22-----------Paid
1-------------33------- ---- yes
2-------------11-----------100
2-------------22--- --------Paid
2-------------33-----------no
3------------- 11-----------200
3-------------22-----------Paid
3--------- ----33-----------no
The task is to write an sql query for a mutually exclusive filter on a table with such a structure.
For example, a person set the first condition for filtering with the value "Paid" (received id_page=1,2,3 ) after the results obtained, adds another condition for filtering by the value "100" (received id_page=1,2) and adds the third condition by value "is" (remains id_page=1) The
question is how to get such a result in one sql query?
I got this query:

SELECT `id_page` FROM `fields_value` WHERE `value` ='есть' AND `id_page` IN (
  SELECT `id_page` FROM `fields_value` WHERE `value` ='100' AND `id_page` IN (
    SELECT `id_page` FROM `fields_value` WHERE `value` ='Платные'
    )
)

Such a query works correctly and the result shows the correct one, but how correct is this output?
That is, let's say in the table there will be not 3 possible id_pages, but let's say 1-2 thousand and conditions for filtering not 3 but 10 pieces, wouldn't such a request be too long in such conditions? if done at all.
If there is another option please advise.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2014-07-11
@victorib_us

SELECT DISTINCT `res`.`id_page` FROM `fields_value` AS `res`
  INNER JOIN `fields_value` AS `f1` ON (`f1`.`id_page` = `res`.`id_page` AND `f1`.`id_field` = 22 AND `f1`.`value` = 'Платный')
  INNER JOIN `fields_value` AS `f2` ON (`f2`.`id_page` = `res`.`id_page` AND `f2`.`id_field` = 11 AND `f2`.`value` = '100')
  INNER JOIN `fields_value` AS `f3` ON (`f3`.`id_page` = `res`.`id_page` AND `f3`.`id_field` = 33 AND `f3`.`value` = 'есть')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question