2014-02-14 68 views
1

我有这个表:为相同的列名,但具有不同值的Mysql Select查询

id sh_id meta_key meta_value 
1 1 country 111 
2 1 state  10 
3 1 city  5 
4 2 country 110 
5 4 state  11 
.... 

我将一个数组值传递给函数。和数组包含类似下面

$array = array('country_id'=>111,'state_id'=>10,'city_id'=>1); 

function getValue($array) 

我想这些阵列值的结果应与meta_key和meta_value

例如匹配值:查询匹配与阵列与COUNTRY_ID值meta_key和meta_key'国家'以及州和城市

它应该在一个查询中。

我曾尝试下面的查询,它不工作

$this->db->where('meta_key', 'country'); 
$this->db->or_where('meta_value', $array['country_id']); 
$this->db->where('meta_key', 'state'); 
$this->db->or_where('meta_value', $array['state_id']); 
$query = $this->db->get("at_featured_shops"); 

回答

2

你可以做这样的事情:

<?php 
$array = array(
    'country' => 111, 
    'state' => 10, 
    'city' => 5 
); 

function getValue($array) { 

    $where = 'WHERE '; 

    $or = ''; 
    foreach($array as $key => $value) { 
     $where .= $or."(meta_key = '".$key."' AND meta_value = '".$value."')"; 
     $or = ' OR '; 
    } 
    $query = $this->db->query("SELECT * FROM table ".$where); 

} 

getValue($array); 

?> 
相关问题