Search code examples
mysqlsqljoininner-joinrelational-division

SQL use of conditional AND on a join table to ensure at least two or multiple values are matched


I have a join table named languages_services that basically joins the table services and languages.

I need to find a service that is able to serve both ENGLISH (language_id=1) and ESPANOL (language_id=2).

table languages_services
------------------------
service_id | language_id
------------------------
 1         |  1
 1         |  2
 1         |  3
 2         |  1 
 2         |  3

With the data provided above, I want to test for language_id=1 AND language_id=2 where the result would look like this

QUERY RESULT
------------
service_id
------------
 1

Obviously it doesn't return the one with service_id=2 because it doesn't service Espanol.

Any tips on this is greatly appreciated!


Solution

  • SELECT
      service_id
    FROM
      language_services
    WHERE
         language_id = 1
      OR language_id = 2
    GROUP BY
      service_id
    HAVING
      COUNT(*) = 2
    

    Or...

    WHERE
      lanaguage_id IN (1,2)
    GROUP BY
      service_id
    HAVING
      COUNT(*) = 2
    

    If you're always looking at 2 languages you could do it with joins, but the aggregate version is easier to adapt to differing numbers of language_ids. (Add an OR, or add an item to the IN list, and change the COUNT(*) = 2 to COUNT(*) = 3, etc, etc).

    Be aware, however, that this scales very poorly. And with this table structure there isn't much you can do about that.


    EDIT Example using a join for 2 languages

    SELECT
      lang1.service_id
    FROM
      language_services   AS lang1
    INNER JOIN
      language_services   AS lang2
        ON lang1.service_id = lang2.service_id
    WHERE
          lang1.language_id = 1
      AND lang2.language_id = 2