Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something in MySQL like IN but which uses AND instead of OR?

Tags:

sql

mysql

I need a SQL statement to retrieve records where it key (or any column) is in a associate table, for example:

documentId termId
4             1
4             2
3             3
5             1

This:

SELECT documentId 
  FROM table 
 WHERE termId IN (1,2,3)

...will retrieve any documentid value where the termid value is 1 or 2 or 3.

Is there something like this but return documentid values where the termid values are 1 and 2 and 3? Like an IN but with AND.

like image 554
Skatox Avatar asked May 18 '10 19:05

Skatox


People also ask

Can we use in with like in MySQL?

The MySQL LIKE OperatorThe LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters.

Can we use like and in operator in SQL?

There is no combination of LIKE & IN in SQL, much less in TSQL (SQL Server) or PLSQL (Oracle). Part of the reason for that is because Full Text Search (FTS) is the recommended alternative.

What does <> mean in MySQL?

The symbol <> in MySQL is same as not equal to operator (!=). Both gives the result in boolean or tinyint(1). If the condition becomes true, then the result will be 1 otherwise 0. Case 1 − Using !=

What is the difference between in and like in MySQL?

= in SQL does exact matching. LIKE does wildcard matching, using '%' as the multi-character match symbol and '_' as the single-character match symbol. '\' is the default escape character. foobar = '$foo' and foobar LIKE '$foo' will behave the same, because neither string contains a wildcard.


1 Answers

There's no straight forward functionality, but there are two options:

Using GROUP BY/HAVING


  SELECT t.documentid
    FROM TABLE t
   WHERE t.termid IN (1,2,3)
GROUP BY t.documentid
  HAVING COUNT(DISINCT t.termid) = 3

The caveat is that you have to use HAVING COUNT(DISTINCT because duplicates of termid being 2 for the same documentid would be a false positive. And the COUNT has to equal the number of termid values in the IN clause.

Using JOINs


SELECT t.documentid
  FROM TABLE t
  JOIN TABLE x ON x.termid = t.termid
              AND x.termid = 1
  JOIN TABLE y ON y.termid = t.termid
              AND y.termid = 2
  JOIN TABLE z ON z.termid = t.termid
              AND z.termid = 3

But this one can be a pain for handling criteria that changes a lot.

like image 77
OMG Ponies Avatar answered Sep 27 '22 20:09

OMG Ponies