MySQL – Select Data Where Column Value Exists in Separate Rows

MySQLselect

This is on a MySQL database. Locations have services.

What I want is to get all results where service_id is 2 AND 3, not OR so using IN is out I believe.

Database

----------------------------
| location_id | service_id |
----------------------------
|      1      |      2     |
|      1      |      3     |
|      2      |      2     |
----------------------------

Expected Results

----------------------------
| location_id | service_id |
----------------------------
|      1      |      2     |
|      1      |      3     |
----------------------------

Best Answer

Here's your query:

SELECT
   T.location_id,
   GROUP_CONCAT(T.service_id) AS serviceids
FROM `Table` AS T
GROUP BY T.location_id
HAVING serviceids IN ('2,3');

You could use ORDER BY inside the GROUP_CONCAT():

SELECT 
   T.location_id,
   GROUP_CONCAT(T.service_id ORDER BY service_id ASC) AS serviceids
FROM `Table` AS T
GROUP BY T.location_id
HAVING serviceids IN ('2,3');

EDIT, Another way:

SET @LOCATION_ID=0;
SET @LOCATION_ID=(
    SELECT
        T.location_id
    FROM `Table` AS T
    GROUP BY T.location_id
    HAVING GROUP_CONCAT(T.service_id ORDER BY T.service_id ASC) LIKE '%2,3%');
SELECT
    T.location_id,
    T.service_id
FROM `Table` AS T
WHERE T.service_id IN (2,3) AND T.location_id=@LOCATION_ID;

Result:

enter image description here

Hope this help.