仅在设置变量时使用 SELECT 运算符 'AND'

Using the SELECT operator 'AND' only if a variable is set

如果设置了变量,correct/efficient 基于变量显示结果的方法是什么?如果未设置变量,则不应使用 AND 运算符。

如果这是重复,我深表歉意,我点击了建议的链接,但它们对我来说没有意义。

接近代码末尾的是我的笔记,带有 ^^^^^ 标记。

例如:

$whatever = 123;

SELECT  
DISTINCT terms.name as product_type_name,
tax.term_id as termidouter

FROM        $wpdb->posts AS p

INNER JOIN wp_term_relationships r
ON p.ID = r.object_id

INNER JOIN wp_term_taxonomy tax
ON r.term_taxonomy_id = tax.term_taxonomy_id

INNER JOIN wp_terms terms
ON tax.term_id = terms.term_id

WHERE
tax.taxonomy = 'product_type'

AND         p.post_status = 'publish'
AND         p.post_type = 'product'
AND         '$whatever ' = terms.term_id
^^^^ If $whatever is empty, I want to return results as if this line did not exist.

ORDER BY product_type_name
");

我本来打算做一个 IF/ELSE,但我认为那是懒惰的方式。

$whatever = 123;

if (empty($whatever)) {
    // SELECT without the AND
} else {
    // SELECT with the AND
}

你可以这样做:

AND CASE WHEN '$whatever ' IS NOT NULL THEN '$whatever ' ELSE terms.term_id END = terms.term_id

所以...通常您希望使用准备好的语句,但如果我们要走这条路,我会将所有可选的搜索条件作为字符串收集在一个数组中:

$myTerms=array();
if(!empty($whatever)) {
    $myTerms[]="terms.term_id='" . $whatever . "'";
}
...

然后您可以像这样轻松构建查询:

$mySql = "SELECT * FROM whatever WHERE somefield='somevalue' ";
if(count($myTerms)>0) {
    $mySql.=" AND " . implode(" AND ", $myTerms);
}

请注意,这是一个基本示例;您还应该检查传递给查询的任何值是否存在攻击等。