简体   繁体   中英

Mysql Select query for same column name but with different values

I have this table:

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
....

I will pass an array value to the function. and the array contains value like below

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

function getValue($array)

I want to get the result of those array values should match with the meta_key and the meta_value

For example : The query match with the country_id value of the array with the meta_value and the meta_key 'country' as well as state and city

It should be in one query .

I have tried the below query and it's not working

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

You can do something like this:

<?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);

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM