Skip to content
Advertisement

Getting all rows with common value in column A and specific value in column B

In MySQL I have table matcher_table with columns matcher and type. Records which are put here can have many different values for type column. One type matches another one only when value for matcher column is the same.
Let’s say I have to find all matching records for 5 types. Which would be the best approach/query in order to achieve this?


The table would be:

Now let’s say we have this values in the table:

If I need to get matching data for types (type1, type2, type3), than I must get rows with ID 1, 2, 3, 6, 7, 8 (due to match1 and match3).
If I need to get matching data for types (type1, type2, type3, type4) than I must get no records fulfilling this match.

Advertisement

Answer

I would recommend three exists clauses — because you want the original rows:

The advantage of this approach is that it avoids aggregation and it can make use of an index on matcher_table(matcher, type). I would expect this to have very good performance in comparison to other approaches.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement