D
D
Dmitry Baibukhtin2019-03-27 17:10:29
MySQL
Dmitry Baibukhtin, 2019-03-27 17:10:29

How to find records with suitable parameters?

Good afternoon.
There are filter subscriptions.
Table with subscriptions subscriptions: id, email
1, [email protected]
Table with possible filters subscriptions_filters: id, code, name
1, brand, Car brand
2. model, Model
3. power_from, Power from
Table subscriptions_filters_values: id, subscription_id, filter_id, value
1, 1, 1, BMW
2, 1, 2, M5
If I were to find all subscriptions that have a BMW car make, M5 model, and power of 155, then the query would be simple.

SELECT * FROM subscriptions as sb
LEFT JOIN subscriptions_filters_values as sfv ON sfv.subscription_id = sb.id
LEFT JOIN subscriptions_filters as sf ON sf.id = sfv.filter_id
WHERE (sf.code = 'brand' and sfv.value = 'BMW') AND (sf.code = 'model' and sfv.value = 'M5') AND (sf.code = 'power' and sfv.value = '155')

What should I do if I need to find all BMW M5 155 hp subscriptions, but also those with some of the parameters not set? For example, a subscription to a filter that lists only BMW, without model and power.
UPD:
And although even the request above will not work, because it is not correct. Do you have options? I don’t know how to decide at all, except how to select all filters from the database and compare in PHP ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2019-03-27
@PiloTeZ

Your request is not correct because where is a contradiction - how sf.code can be both brand and model, etc. in one entry?
To make it correct, you need to put OR between the brackets, not and.
For an incomplete condition, simply remove the bracket with the corresponding condition from the query.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question