2013-06-05 30 views
-1

我試圖在使用codeigniter時加入兩個表。我已經完成了編寫常規SQL的相同SQL查詢。當我嘗試在codeigniter中做同樣的事情時,我不斷收到錯誤。我不太確定我做錯了什麼。你們認爲我做錯了什麼?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

爲什麼你在CI版本中加入'join'?其實,爲什麼*不*你有另一個呢? – Shomz

回答

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(); 
0

夫婦的問題:你需要包括你的表的別名和您的加入應該有第二個表的名稱...

$this->db->from('tbl_car_description AS d'); 
$this->db->join('tbl_car_prices AS p', 'd.id = p.cardescription_id');