我很困惑如何在MySQL查询中创建循环。
我有这个问题:
<?php
$arr = explode(',', $features);
$query_spicy = "
SELECT wposts.*
FROM $wpdb->posts wposts
INNER
JOIN ( SELECT post_id
FROM $wpdb->postmeta wpostmeta
WHERE (';
( wpostmeta.meta_key = 'features' AND wpostmeta.meta_value LIKE '%test1%' )
OR
( wpostmeta.meta_key = 'features'AND wpostmeta.meta_value LIKE '%test2%' )
OR
( wpostmeta.meta_key = 'features'AND wpostmeta.meta_value LIKE '%test3%' )
OR
( wpostmeta.meta_key = 'features'AND wpostmeta.meta_value LIKE '%test4%' )
OR
( wpostmeta.meta_key = 'features'AND wpostmeta.meta_value LIKE '%test5%' )
')
GROUP BY post_id
) AS t ON t.post_id = wposts.ID WHERE wposts.post_status = 'publish' AND wposts.post_type = 'book' ORDER BY wposts.post_date DESC";
?>
我想用for循环生成波纹管部分动态:
( wpostmeta.meta_key = 'features' AND wpostmeta.meta_value LIKE '%test1%' ) OR
( wpostmeta.meta_key = 'features' AND wpostmeta.meta_value LIKE '%test2%' ) OR
( wpostmeta.meta_key = 'features' AND wpostmeta.meta_value LIKE '%test3%' ) OR
( wpostmeta.meta_key = 'features' AND wpostmeta.meta_value LIKE '%test4%' ) OR
( wpostmeta.meta_key = 'features' AND wpostmeta.meta_value LIKE '%test5%' )
注意:test1,test2,test3,test4和test5,我来自$arr
。
我希望你理解我的问题,如果你帮助我,我会感激的。
谢谢:)
答案 0 :(得分:2)
尝试类似
的内容$arr = explode(',', $features);
$conditions = array();
foreach($arr as $feature){
$condition[] = "( wpostmeta.meta_key = 'features' AND wpostmeta.meta_value LIKE '{$feature}' )";
}
$query = "SELECT ...". join("OR",$conditions);
但你可以简单地做一些像wpostmeta.meta_key ='feature'和wpostmet IN($ features)
我认为第二种解决方案更好更快。
答案 1 :(得分:0)
试试这个
wpostmeta.meta_key =&#34;。$ features。&#34;和wpostmeta.meta_value LIKE&#39;%test1%&#39;
答案 2 :(得分:0)
<?php
$arr = explode( ',', $features );
$query_spicy = "
SELECT wposts.*
FROM {$wpdb->posts wposts}
INNER
JOIN ( SELECT post_id
FROM {$wpdb->postmeta wpostmeta}
WHERE (";
$tmp = array();
foreach( $arr as $value )
{
$tmp[] = "( wpostmeta.meta_key = 'features' AND wpostmeta.meta_value LIKE '%{$value}%' )";
}
$query_spicy .= implode( ' OR ', $tmp );
$query_spicy .= ")
GROUP BY post_id
) AS t ON t.post_id = wposts.ID WHERE wposts.post_status = 'publish' AND wposts.post_type = 'book' ORDER BY wposts.post_date DESC";
?>
答案 3 :(得分:-1)
FWIIW:
只需设置一个数组以包含您需要插入的数据,然后使用foreach循环遍历它。
$sql="SELECT wposts.*
FROM $wpdb->posts wposts
INNER
JOIN ( SELECT post_id
FROM $wpdb->postmeta wpostmeta
WHERE ('; ";
foreach($arrayoftestdata as $test)
{
$sql.="( wpostmeta.meta_key = 'features' AND wpostmeta.meta_value LIKE '%$test%' ) OR ";
}
$sql.="')
GROUP BY post_id
) AS t ON t.post_id = wposts.ID WHERE wposts.post_status = 'publish' AND wposts.post_type = 'book' ORDER BY wposts.post_date DESC";