Mysql选择相同列名但具有不同值的查询

时间:2014-02-14 05:26:54

标签: php 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匹配

例如:查询与带有meta_value和meta_key'country'以及州和城市的数组的country_id值匹配

它应该在一个查询中。

我已经尝试了以下查询,但它无效

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

1 个答案:

答案 0 :(得分: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);

?>