doumeba0486 2014-03-26 08:26
浏览 325
已采纳

MYSQL - 选择值等于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?

  • 写回答

2条回答 默认 最新

  • doucheng9634 2014-03-26 09:33
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据