我正在处理一个具有可选过滤器的查询,因此假设表名为products,过滤器为id (主键)
如果过滤器不存在,我会这样做:
SELECT * FROM products;
如果过滤器存在,我需要这样做:
SELECT * FROM products WHERE id = ?;
我已经找到了一些潜在的解决方案,它们可以在sql中混合使用2,而不是在后端代码本身中处理条件
SELECT * FROM products WHERE id = IF(? = '', id, ?);
或
SELECT * FROM products WHERE IF(? = '',1, id = ?);
我只是想知道哪一个会更快(在多个过滤器或非常大的表的情况下),或者有更好的解决方案来处理这种情况?
发布于 2018-06-14 01:21:25
最简单的方法是OR
SELECT *
FROM products
WHERE (? IS NULL OR id = ?);
请注意,由于您将使用AND
添加越来越多的条件,因此生成的计划至少会很差。没有万能的解决方案。如果可能,您应该使用条件逻辑构建查询。
更多信息:The “Kitchen Sink” Procedure (SQL Server - but idea is the same)
发布于 2018-06-14 05:19:48
一种更好的方法是根据可用的参数构造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
...";
https://stackoverflow.com/questions/50842934
复制相似问题