【问题标题】:Using the SELECT operator 'AND' only if a variable is set仅当设置了变量时才使用 SELECT 运算符“AND”
【发布时间】:2017-12-30 07:10:06
【问题描述】:

如果设置了变量,那么基于变量显示结果的正确/有效方式是什么?如果未设置变量,则不应使用 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 ($whatever = terms.term_id OR $whatever IS NULL)

标签: sql variables if-statement operator-keyword


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 谢谢。我理解这部分: CASE WHEN '$whatever ' IS NOT NULL THEN '$whatever ' 但我不明白 ELSE。简单地让 terms.term_id = terms.term_id 什么都不会发生?
  • @LITguy 是的,如果 '$whatever 没有被填充,过滤子句变成了 terms.term_id = terms.term_id,这基本上是一个冗余过滤器,因为它总是正确的。您的查询将返回结果,就好像该行不存在一样:)
  • 标记为答案。工作得很好,我很感激你的解释!
  • @LITguy 谢谢 :)
【解决方案2】:

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

$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);
}

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

【讨论】:

  • 这也是一个很好的答案。
猜你喜欢
  • 2022-12-10
  • 1970-01-01
  • 2012-12-19
  • 1970-01-01
  • 2013-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多