Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL subset operation

Tags:

sql

mysql

Is there a way to achieve something like:

SELECT *
FROM tb_values
WHERE (value1, value2, value3) SUBSET_OF
    ( SELECT value
      FROM tb_value
      WHERE isgoodvalue = true
    )

More information: I have a table called projects. Each project has tags. A tag can be shared by multiple projects. There is a mapping table called projectTagMap. Now users use tags to filter the projects. Tags are selected using checkboxes on the UI. So a user selects several tags to filter the projects. Am supposed to select the projects from projects table that contains all the tags selected by the user.

like image 915
joshua Avatar asked Sep 06 '25 22:09

joshua


1 Answers

From your pseudo code I guess that you want to check if a (dynamic) list of values is a subset of another list provided by a SELECT. If yes, then a whole table will be shown. If not, no rows will be shown.

Here's how to achieve that:

SELECT *
FROM tb_values
WHERE 
    ( SELECT COUNT(DISTINCT value)
      FROM tb_value
      WHERE isgoodvalue = true
        AND value IN (value1, value2, value3)
    ) = 3

UPDATED after OP's explanation:

SELECT *
FROM project
  JOIN 
    ( SELECT projectid
      FROM projectTagMap
      WHERE isgoodvalue = true
        AND tag IN (tag1, tag2, tag3)
      GROUP BY projectid
      HAVING COUNT(*) = 3
    ) AS ok
    ON ok.projectid = project.id
like image 164
ypercubeᵀᴹ Avatar answered Sep 09 '25 03:09

ypercubeᵀᴹ