J
J
jemanov2018-07-12 08:21:53
MySQL
jemanov, 2018-07-12 08:21:53

How to make a selection from a Mysql table by a field with multiple values?

How to be, there are three tables
1. cities

id | name
--------------
1  | Moskow
2  | Kirow
3  | Orel
....

2 categories
id | name
--------------
1  | name1
2  | name2
3  | name3
...

And there is a third table - a list of companies:
id  |    name   |  cities_id   |    categories_id
----------------------------------------------------
1   | alpha     | 1,2,5,18     | 3,76,78
2   | betta     | 2,14,31      | 13,60,75
3   | gamma     | 1,17,19      | 95,101
....

The question is:
How convenient is it to make a selection of companies by city, category, city and category together, if each company can work in several cities and perform several categories of work?
options from 1930 cities, 285 categories.
I used to use:
- FILD_IN_SET() but now there are more than 64 values ​​and this option is not suitable.
- ENUM doesn't work either, since the fields cities_id and categories_id can contain several values ​​​​at once
- I translated all this into a multidimensional array and then looked for it in php.
- did all sorts of WHERE cities_id LIKE '%,5,%' OR cities_id LIKE '5,%' OR cities_id LIKE '%,5' (as well as options with adding commas at the beginning and end of the field to reduce the number of ORs).
- they also advised to link the tables, but how to do this when there are several values ​​\u200b\u200bin cities_id and categories_id, and how then to choose based on these links, I could not figure it out (I did not find normal examples, because I did not even know what to look for, and whether is that what you need?)
Are there beautiful solutions that are used in a professional environment, or is everyone sculpting like me?
Explain, guru, I really want to understand.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2018-07-12
@qonand

deal with the normal forms of the database and reverse-engineer the normal database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question