gpt4 book ai didi

php - 是否可以在 MYSQL AND "clause"中使用 IF ELSE

转载 作者:行者123 更新时间:2023-11-29 08:38:26 26 4
gpt4 key购买 nike

我下面的示例“显然”不起作用::: 有没有办法获得 IF ELSE 或类似的工作::: 我有几个 PHP 变量,基于这些变量我想更改此查询中的 AND“子句”,而不必创建多个查询并使用 PHP if 语句来使用正确的查询 block :::

$query = "SELECT $wpdb->posts.ID
FROM $wpdb->posts
INNER JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id)
WHERE 1=1
AND $wpdb->posts.post_type = 'cars'
AND ($wpdb->posts.post_status = 'publish' OR $wpdb->posts.post_status = 'private')

IF ( $drive )
AND ( ($wpdb->postmeta.meta_key = 'vehicle_year' AND CAST($wpdb->postmeta.meta_value AS CHAR) = '$year')
ELSEIF ( $fuel )
AND ( ($wpdb->postmeta.meta_key = 'vehicle_fuel' AND CAST($wpdb->postmeta.meta_value AS CHAR) = '$fuel')
ENDIF

AND ( ($wpdb->postmeta.meta_key = 'vehicle_fuel' AND CAST($wpdb->postmeta.meta_value AS CHAR) = '$fuel') )
GROUP BY $wpdb->posts.ID
ORDER BY $wpdb->posts.post_date
DESC LIMIT 0, 99";

最佳答案

$p="";
$q="";
if( empty($drive) ){
$p=" AND ( ($wpdb->postmeta.meta_key = 'vehicle_year' AND CAST($wpdb->postmeta.meta_value AS CHAR) = '$year')";
}else{
if( empty($fuel) ){
$q=" AND ( ($wpdb->postmeta.meta_key = 'vehicle_fuel' AND CAST($wpdb->postmeta.meta_value AS CHAR) = '$fuel')";
}
}

$query = "SELECT $wpdb->posts.ID
FROM $wpdb->posts
INNER JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id)
WHERE 1=1
AND $wpdb->posts.post_type = 'cars'
AND ($wpdb->posts.post_status = 'publish' OR $wpdb->posts.post_status = 'private')
".$p.$q."
AND ( ($wpdb->postmeta.meta_key = 'vehicle_fuel' AND CAST($wpdb->postmeta.meta_value AS CHAR) = '$fuel') )
GROUP BY $wpdb->posts.ID
ORDER BY $wpdb->posts.post_date
DESC LIMIT 0, 99";

关于php - 是否可以在 MYSQL AND "clause"中使用 IF ELSE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14545794/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com