简体   繁体   中英

MYSQL - Select elements where value equal to any

Imagine a simple query, where $value is a boolean variable:

"SELECT * FROM table where table.value = {$value}";

It's easy to filter the selection for $value equal to true or equal to false .

The question is: how could I filter by ANY ( true or false ) in the same query?

Sets of values and comparison

There's a field of some data type which can take some set of values ( ENUM is very good example, but not only example). So if you want to compare by some subset of values, you can use IN :

SELECT * FROM t WHERE v IN ($values)

here $values stands for set of values, not one value. Set of values is delimited by comma, thus, if you have array:

$values = [1, 2, 5];

then you need to query like:

//values escaping is needed, but out of this issue:
$query = 'SELECT * FROM t WHERE v IN ('.join(',', $values).')';

Also, string literals have to be enclosed by quotes - therefore, construction above should be modified for them like:

$values = ['foo', 'bar'];
$inSet  = array_map(function($x)
{
   return '"'.$x.'"';
}, $values);
$query = 'SELECT * FROM t WHERE v IN ('.join(',', $inSet).')';

Current case

There is, however, one case when comparison above won't be needed. It's like your question. In your case, your data type full set is equal to subset of values in comparison. Thus, whole condition makes no sense - because data type can not hold anything out of it's full set of values. Thus, you can either omit your condition at all or leave WHERE 1 (if having WHERE is mandatory).

SELECT * FROM tablе;
SELECT * FROM table where value = 0 OR value = 1;
SELECT * FROM table where (value = 0 OR value = 1) -- AND (other where conditions); (remove -- to uncomment)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM