Search code examples
mysqlsqlfiltergroup-concat

SQL filtering using an array


I have the following tables in my database:

Table: Employee

ID      Name
--      ----
1       Mike
2       Peter
3       Daniel

Table: Location

EmployeeID      City
----------      ----
1               Berlin
1               Stuttgart
1               München
2               Hamburg
3               Stuttgart
3               Berlin

The Employee table contains information about the employees. The Location table contains information about the locations the employees have their projects in (e.g Mike has projects in Berlin, Stuttgart, and München).

What I want to do now is to filter employees by given locations in an array but still retrieve all the locations of each employee. For example, filtering by the array ["Berlin", Stuttgart] should return the following result:

ID      Name      City
--      ----      ----
1       Mike      Berlin, Stuttgart, München
3       Daniel    Stuttgart, Berlin

I know that I can use GROUP_CONCAT() to concatenate the locations. But how can I do the filtering? I need to be able to do it using SQL.


Solution

  • Apply WHERE condition to get EmployeeID from Location table:

    SELECT 
      Employee.*, 
      GROUP_CONCAT(Location.City) 
    FROM 
      Employee 
        INNER JOIN Location 
          ON Employee.ID=Location.EmployeeID 
        INNER JOIN 
          (SELECT DISTINCT 
            EmployeeID 
           FROM 
             Location 
           WHERE 
             City IN ('Berlin', 'Stuttgart')) AS IDS
          ON Employee.ID=IDS.EmployeeID
    GROUP BY 
      Employee.ID
    

    -check the fiddle.

    Alternative solution would be to use HAVING clause with plain query and INSTR(), for example, but I don't recommend you to do it because comparing in HAVING will be slow and, besides, list of values will produce multiple comparisons.