带有可选过滤器的MySQL查询

时间:2014-03-12 14:08:37

标签: php mysql

我的桌子上有一栏' x'这是1或0.我需要一个MySQL查询返回所有行,或者x = 1或x = 0的那些行。

我想要的那三个结果中的哪一个设置在变量$ type中。我所做的是创建三个查询和一个if子句:

if ($type == 'all') $query = "SELECT * FROM contracts";
elseif ($type == 'n') $query = "SELECT * FROM contracts WHERE x = '0'";
elseif ($type == 'f') $query = "SELECT * FROM contracts WHERE x = '1'";

这有效,但我似乎不是最好的解决方案,因为我必须写3次几乎相同的查询,如果我想改变一些东西,我必须改变它3次。

我尝试制作$ type ='',0或1然后WHERE x = '$type',但这不起作用。

如何只使用一个MySQL查询?

5 个答案:

答案 0 :(得分:1)

if ($type = 'all') {
    $filter = '';
} elseif ($type == 'n') {
    $filter = "WHERE x = '0'";
} elseif ($type == 'f') {
    $filter = "WHERE x = '1'";
} else {
    die("Invalid filter type: $type");
}
$query = "SELECT * FROM contracts $filter";

如果你使用$type = '', 0, or 1的方案,你可以这样做:

$query = "SELECT * FROM contracts";
if ($type !== '') {
    $query .= " WHERE x = '$type'";
}

答案 1 :(得分:0)

switch($type){
    case 'n':
        $where = "WHERE x = '0'";
        break;
    case 'f':
        $where = "WHERE x = '1'";
        break;
    default:
        $where = "";
        break;
}
$query = 'SELECT * FROM contracts '.$where;

答案 2 :(得分:0)

$query = 'SELECT * FROM contracts';
if ($type != 'all')
    $query .= ' WHERE x = \'' . ($type == 'n' ? 0 : 1) . '\'';

答案 3 :(得分:0)

试试这个

$query = "SELECT * FROM contracts" . ($type != 'all' ? (" where x = '" . intval( $type == 'n') . "'") : '')

答案 4 :(得分:0)

由于您正在进行n到0和f到1等的转换,因此在mysql查询中执行此操作将需要不必要的复杂CASE语句。我更喜欢只包含必要的字符串:

if ($type == 'all') $typeLimiter = " ";
elseif ($type == 'n') $typeLimiter = " AND x = '0' ";
elseif ($type == 'f') $typeLimiter = " AND x = '1' ";

这样您就可以在查询中堆叠无限的AND / OR语句:

 $query = "SELECT * FROM contracts 
    WHERE 1 = 1 
    $typeLimiter";

请注意,我将WHERE 1 = 1作为第一个声明,因此可以应用任何/所有/无限制器。