用于搜索查询的MySQL可选过滤器

时间:2018-06-13 17:20:35

标签: mysql database optimization

我正在处理一个具有可选过滤器的查询,因此我们假设表名是products,过滤器是id(主键)

如果过滤器不存在,我会做这样的事情:

SELECT * FROM products; 

如果过滤器存在,我需要做这样的事情:

SELECT * FROM products WHERE id = ?;

我找到了一些可以在sql中混合2而不是在后端代码本身中做条件的潜在解决方案

SELECT * FROM products WHERE id = IF(? = '', id, ?);

OR

SELECT * FROM products WHERE IF(? = '',1, id = ?);

我只是想知道哪一个更快(在多个过滤器或非常大的表的情况下)或者是否有更好的解决方案来处理这种情况?

2 个答案:

答案 0 :(得分:0)

最简单的方法是OR

SELECT * 
FROM products 
WHERE (? IS NULL OR id = ?);

请注意,由于您将使用AND添加越来越多的条件,因此生成的计划至少会很差。没有适合他们的解决方案。如果可能,您应该使用条件逻辑构建查询。

更多信息:The “Kitchen Sink” Procedure(SQL Server - but idea is the same)

答案 1 :(得分:0)

更好的方法是从可用参数构造WHERE子句。这使优化器能够做得更好。

$wheres = array();

// Add on each filter that the user specified:
if (! empty($col))     { $s = $db->db_res->real_escape_string($col);
                                       $wheres[] = "collection = '$s'"; }
if (! empty($theme))   { $s = $db->db_res->real_escape_string($theme);
                                       $wheres[] = "theme = '$s'"; }
if (! empty($city))    { $s = $db->db_res->real_escape_string($city);
                                       $wheres[] = "city = '$s'"; }
if (! empty($tripday)) { $s = $db->db_res->real_escape_string($tripday);
                                       $wheres[] = "tripday = '$s'"; }

// Prefix with WHERE (unless nothing specified):
$where = empty($wheres) ? '' :
            'WHERE ' . implode(' AND ', $wheres);

// Use the WHERE clause in the query:
$sql = "SELECT ...
           $where
           ...";
相关问题