We need to select all segments_id, em_id
from the following table mytable
that have a segments_id
of 5 or 8 but not 1 or 7. To be clearer after comments made below, the result will be a set that includes all rows of segments_id, em_id
where em_id
has segments_id
of 5 or 8 BUT not 1 or 7.
+-------------+-------+
| segments_id | em_id |
+-------------+-------+
| 1 | 8 |
| 1 | 17 |
| 5 | 2 |
| 5 | 4 |
| 5 | 5 |
| 5 | 16 |
| 5 | 17 |
| 7 | 4 |
| 7 | 5 |
| 7 | 8 |
| 7 | 16 |
| 8 | 4 |
| 8 | 6 |
| 8 | 8 |
| 8 | 18 |
| 18 | 6 |
| 18 | 99 |
+-------------+-------+
The result should be:
+-------------+-------+
| segments_id | em_id |
+-------------+-------+
| 5 | 2 |
| 8 | 6 |
| 8 | 16 |
+-------------+-------+
We need to avoid using IN
clause because this can scale to millions of rows.
I understand this will involve a join on itself and/or a subquery but I'm not seeing it. I saw this post Stackoverflow: Selecting rows from a table that have the same value for one field but cannot see the solution.