我正在尝试使用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')");
答案 0 :(得分:0)
情侣问题:您需要包含表别名,并且您的联接应该具有第二个表的名称...
$this->db->from('tbl_car_description AS d');
$this->db->join('tbl_car_prices AS p', 'd.id = p.cardescription_id');
答案 1 :(得分: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();