php - 不明确的查询 [codeigniter]

标签 php sql codeigniter activerecord

我有最多三个任意字段(例如“location、crimes 和 food_rating”)和两个任意表名(例如“food 和 crimes”),其中可能包含这些给定字段。

如果一个属性同时存在于两个表中,我会收到一个“不明确”的错误,这是可以理解的。但是,我不太想好如何生成一个查询来检查每个可能的情况,并在可能的情况下加入。

我在 codeigniter 中这样做,到目前为止已经写了以下内容,这会导致错误。我还应该注意,任意字段也可以为空。

$this->db->select($data->att_one . ',' . $data->att_two . ',' . $data->att_three)
->from($data->db_one . ',' . $data->db_two)
->get()
->result_array();

我收到的错误如下:

字段列表中的“location”列不明确 (因为位置在两个表中)

最佳答案

问题歧义,不清楚您想从哪些表中选择什么以及您希望如何填充结果。

如果您希望在一个结果中同时包含“食物”和“犯罪”表中的“位置”,则必须为它们取别名:

$this->db
    ->select('food.location as foodlocation, crimes.location as crimeslocation')
    ->from('food, crimes')
    ->get()
    ->result_array();

根据您对这些结果的处理方式,对每个表使用新查询可能更容易:

$results = array();
$select = array($data->att_one, $data->att_two, $data->att_three);
$tables = array($data->db_one, $data->db_two);

foreach ($tables as $tableName)
{
    $results[$tableName] = $this->db->select($select)
        ->get($tableName)
        ->result_array();
}

这实际上取决于您在做什么,但希望您明白为什么数据库无法理解您的查询。

关于php - 不明确的查询 [codeigniter],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15189855/

相关文章:

mysql - 如何从 SQL 中获取仅以特定值出现的条目?

javascript - 如何使用 PHP 中循环数据内的 post 方法将数据发送到 Controller

php - 检索多个YouTube用户的最新视频并按最新顺序排序

php - 如何防止向MySQL数据库中插入重复数据

php - 使用 mysql 执行许多查询是否可以,还是我应该寻求优化?

SQL 获取特定行中具有特定值的列数

sql - 如何判断一个员工是不是经理?

php - 获取当前 user_id 的产品

php - .htaccess 与 ^(.*)$ index.php/$1 给出 "No input file specified"

php - 使用 jquery 和 php 检索 mysql 数据