Although the question about how to perform bitwise operations in MySQL was answered, the question in the comments about why this model cannot be optimal remains unclear.
In the above example, there are two tables; one with a bitmask and one with a breakdown of what each bit represents. It is understood that at some point the two tables must be joined together to return / display the value of the various bits.
This connection will either be explicit, for example.
SELECT * FROM Table1 INNER JOIN TABLE2 ON table1.ptid & table2.id <> 0
Or implicit, where you can select data from table1 into your application, and then make a second call to search for the values ββof the bitmask, for example.
SELECT * FROM table2 WHERE id & $id <> 0
None of these options is an idea, because they are not "inaccessible", that is, the database cannot build a search ARGument. As a result, you cannot optimize the query using the index. The cost of the query goes beyond the impossibility of using the index, because for each row in the table, the database must calculate and evaluate the expression. This happens very quickly with the intensity of memory, processor, and I / O, and it cannot be optimized without fundamentally changing the table structure.
Besides the complete inability to optimize the query, it can also be inconvenient to read data, report data, and potentially trigger restrictions by adding more bits (64 values ββin an 8-bit column may be accurate now, but not always so. They also make it difficult to understand systems , and I would say that this project violates the first normal form.
Although using bitmasks in a database is often a sign of poor design, there are times when you can use them. The implementation of many-to-many relationships really does not apply to those times.
A typical approach to implementing this type of relationship is something like this:
table1 Id Val1 Val2 --------------------------- 1 ABC DEF 2 ABC DEF 3 ABC DEF 4 ABC DEF 5 ABC DEF 6 ABC DEF table2 id types ------------- 1 music 2 art 3 pictures 4 video 5 art2 6 actor 7 movies table1-table2-relationshitp table1ID Table2ID --------------------- 1 1 1 2 2 3 2 5 3 2 3 7 ...
And you request the data this way
SELECT table1.*, table2.types FROM table1 INNER JOIN table1-table2-relationship ON table1.id = table1-table2-relationship.table1id INNER JOIN table2 ON table1-table2-relationship.table2.id = table2.id
Depending on the access pattern of these tables, you usually index both columns in the relationship table as a composite index (usually I consider them as a composite primary key.) This index will allow the database to quickly search for the corresponding rows in the relations table and then search for the corresponding rows in table2.