-1

我正在尝试在使用 codeigniter 时加入两个表。我已经完成了编写常规 SQL 的相同 SQL 查询。当我尝试在 codeigniter 中做同样的事情时,我不断收到错误。我不太确定我做错了什么。你们觉得我做错了什么?

我在 model_data.php 中的函数

function getJoinInformation($year,$make,$model)
{
 //$this->db->distinct();
 // here is where I need to conduct averages but lets just work on extracting info. 
 // from the database and join tables.
 $this->db->select('*');
 $this->db->from('tbl_car_description');
 $this->db->join('tbl_car_description', 'd.id = p.cardescription_id');
 $this->db->where('d.year', $year);
 $this->db->where('d.make', $make);
 $this->db->where('d.model', $model);
 $result = $this->db->get();
 /*
 $query = $this->db->get_where('tbl_car_description',
  array(
    'year' => $year,
    'make' => $make,
    'model' => $model
   )
  );

  if($query->num_rows()) return $query->result();
  return null;
 */
}

我的错误信息

A Database Error Occurred

Error Number: 1066

Not unique table/alias: 'tbl_car_description'

SELECT * FROM (`tbl_car_description`) JOIN `tbl_car_description` ON `d`.`id` = `p`.`cardescription_id` WHERE `d`.`year` = '2006' AND `d`.`make` = 'Subaru' AND `d`.`model` = 'Baja'

Filename: C:\wamp\www\_states\system\database\DB_driver.php

Line Number: 330

这是用 SQL 编写的代码,它运行良好。我想在codeigniter中做一些事情,但我对如何做感到困惑。任何帮助将非常感激。感谢大家。

$sql_2 = mysql_query("SELECT ROUND(AVG(p.value),1) AS AvgPrice, ROUND(AVG(p.mileage),1) AS AvgMileage
FROM  tbl_car_description d, tbl_car_prices p
WHERE (d.id = p.cardescription_id)
AND (d.year = '".$year."')
AND (d.make = '".$make."')
AND (d.model = '".$model."')
AND (p.approve = '1')");
4

2 回答 2

0

几个问题:您需要包含表别名,并且您的联接应该具有第二个表的名称...

$this->db->from('tbl_car_description AS d');
$this->db->join('tbl_car_prices AS p', 'd.id = p.cardescription_id');
于 2013-06-05T20:39:10.930 回答
0

您的 CI 查询两次引用同一个表,我认为这是一个错字。但是,您只需在 Active Record 调用中包含您的表别名和表名:

 //$this->db->distinct();
 $this->db->select('*');
 $this->db->from('tbl_car_description d');
 $this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
 $this->db->where('d.year', $year);
 $this->db->where('d.make', $make);
 $this->db->where('d.model', $model);
 $result = $this->db->get();
于 2013-06-05T20:39:45.820 回答