2009-04-27 73 views
6

我是PHP/MySQL的新手,並且是CodeIgniter的新手。 我在許多MySQL表中都有信息。我想用JOIN檢索它,其中表主鍵等於$ variable ...我怎樣才能得到所有沒有主鍵字段的字段???CodeIgniter/PHP/MySQL:通過JOIN檢索數據

我現在正在做的是這樣的(只有兩個表連接在這裏):

function getAll($id) { 

    $this->db->select('*'); 
    $this->db->from('movies'); 
    $this->db->join('posters', 'movies.id= posters.id'); 
    // WHERE id = $id ... goes here somehow... 
    $q = $this->db->get(); 

    if ($q->num_rows() == 1) { 
     $row = $q->row(); 
     $data = array(
       'id' => $row->id, 
       'title' => $row->title, 
       'year' => $row->year, 
       'runtime' => $row->runtime, 
       'plotoutline' => $row->plotoutline, 
       'poster_url' => $row->poster_url 
      ); 
    } 

    $q->free_result(); 
    return $data; 

ID(PK),名稱,年份,運行時間和plotoutline從第一表列和poster_url是場從第二張桌子。第二個表格還包含我不想檢索的ID(PK)列,因爲我已經有了。

回答

21

喬恩是對的。這裏有一個例子:

$this->db->select('movies.id, 
        movies.title, 
        movies.year, 
        movies.runtime as totaltime, 
        posters.poster_url'); 
$this->db->from('movies'); 
$this->db->join('posters', 'movies.id= posters.id'); 
$this->db->where('movies.id', $id); 
$q = $this->db->get(); 

這將返回所有的對象 - > ID, - >標題 - >年 - > totalTime和 - > poster_url性能。您將不需要額外的代碼來從每一行中獲取數據。

不要忘記,如果Active Record的語法變得有點笨重,你可以使用完整的SQL查詢,並得到相同的結果:

$sql = "SELECT movies.id, 
     movies.title, 
     movies.year, 
     movies.runtime as totaltime, 
     posters.poster_url 
     FROM movies 
     INNER JOIN posters ON movies.id = posters.id 
     WHERE movies.id = ?" 

return $this->db->query($sql, array($id))->result(); 

這兩種形式都將確保您的數據被正確地轉義。

CodeIgniter Active Record

Query Binding in CodeIgniter

+0

這樣,我將在兩個表之間的連接,並得到所有的結果嗎?我怎樣才能從我想要獲取數據的行中指定ID?就像'WHERE movies.id = $ id'.. – Jonathan 2009-04-28 13:42:09

4

星號將返回所有字段。要返回其中的一個子集,即所有字段都與重複的id字段分開,只需列出您需要的列而不是使用'*'。

無論如何不使用星號通常是一個好主意。在應用程序的未來,有人可能會增加一個大的字段到表中,這將超出您的要求,並會減慢您的查詢速度。

1

簡單地說與方法鏈接:

$this->db->select('*') 
     ->from('movies') 
     ->join('posters', 'movies.id= posters.id') 
     ->where('movies.id', $id) 
     ->get(); 
0
$this->db->select('*'); 
$this->db->from('blogs'); 
$this->db->join('comments', 'comments.id = blogs.id'); 
$query = $this->db->get();