如何在sql中的IN子句中使用数组值

时间:2016-09-09 07:08:21

标签: php mysql

在where子句中,我在$ values变量上获得一个id,而$ rest_id中存在四个id。如何解决这个问题,我可以得到where子句中的所有四个id。请任何人帮忙解决这个问题。第

foreach ($rest_id as $value) 
{
$ids = array($value->id);
$nearest_rest = "SELECT *, (3956 * 2 * ASIN(SQRT( POWER(SIN(( 28.5812674 - lat) * pi()/180 / 2), 2) +COS( 28.5812674 * pi()/180) * COS(lat * pi()/180) * POWER(SIN(( 77.3181059 - lng) * pi()/180 / 2), 2) ))) as distance 
                   FROM restaurant_details 
                  WHERE id In ('" . implode("','",$ids) . "') 
                 HAVING distance 
               ORDER BY distance ASC 
                  LIMIT 1"; 
}

2 个答案:

答案 0 :(得分:0)

// first - take all ids to `$ids` array:
$ids = array();
foreach ($rest_id as $value) {
    $ids[] = $value->id;
}
// then do your query:
$nearest_rest = "SELECT *, (3956 * 2 * ASIN(SQRT( POWER(SIN(( 28.5812674 - lat) * pi()/180 / 2), 2) +COS( 28.5812674 * pi()/180) * COS(lat * pi()/180) * POWER(SIN(( 77.3181059 - lng) * pi()/180 / 2), 2) ))) as distance from restaurant_details where id In ('" . implode("','",$ids) . "') having distance order by distance asc limit 1"; 

答案 1 :(得分:0)

您好在查询中使用ID数组请尝试以下解决方案。

foreach ($rest_id as $value) {
    $ids[] = $value->id;
}

//Than now write your query this way
$nearest_rest = "SELECT *, (3956 * 2 * ASIN(SQRT( POWER(SIN(( 28.5812674 - lat) * pi()/180 / 2), 2) +COS( 28.5812674 * pi()/180) * COS(lat * pi()/180) * POWER(SIN(( 77.3181059 - lng) * pi()/180 / 2), 2) ))) as distance from restaurant_details where id In (" . implode(",",$ids) . ") having distance order by distance asc limit 1";