1

我正在尝试创建一个仅基于许多条件创建数组的 SQL 查询和/或 php 代码。我有一个这样的数组:

Array ( [1] => 1 [8] => 0 [2] => 1 )

The [1] refers to 'question_id' with the 1 being a 'value'
The [8] refers to 'question_id' with the 0 being a 'value'
The [2] refers to 'question_id' with the 1 being a 'value'

我的数据库设置如下,当我调用它时,我试图获取一个仅满足上述所有 ^ 的电影 ID 的数组。所以说数组有[8] => 0。question_id应该是8,对应于该记录的值应该是0。所以说数组有1 => 0。question_id应该是1,对应于该记录的值应该是 0。如果它遇到该对,以及它之前的其他对,它应该将该记录添加到数组中。

我已经尝试过了,我正在使用 Codeigniter:

foreach($array as $key=>$value){
        $this->db->where('question_id', $key);
        $this->db->where('value', $value);
        $this->db->from('movies_values');
        $query = $this->db->get();
        $res = $query->result();
        array_push($main_array,$res);
        }

$main_array 之前是一个空数组。$array 是一个类似于上面的数组。但问题是,它检查一对,所以说1 => 0,如果匹配,则添加它。而不是检查它是否也匹配 [8] => 0 和 [2] => 1。

在此处输入图像描述

4

2 回答 2

2

您可以遍历数组以构建完整的CASE语句

$query = <<<SQL
    SELECT
        movie_id, question_id, value
    FROM
        t1
    WHERE
        CASE
SQL;
$params = array();
foreach ($array as $question_id => $value) {
    $query .= " WHEN question_id = ? THEN value = ? ";
    $params[] = $question_id;
    $params[] = $value;
}
$query .= " END";

http://sqlfiddle.com/#!2/741ff/2

于 2013-02-24T00:33:45.963 回答
0

My advice is to use the data from $array in a where_in(); statement so you can avoid running SQL queries in a loop.

$this->db->where_in('question_id', array_keys($array) );
$this->db->where_in('value', array_values($array) );

which is equivalent to:
SELECT * FROM <table> WHERE question_id IN (array_keys($array)) AND value IN (array_values($array));

于 2013-02-24T01:05:22.813 回答