2012-04-05 60 views
0

我正在嘗試在codeigniter中執行聯合。我發現在別處這個代碼骨架:Union Activerecord codeigniter框架

$this->db->select('title, content, date'); 
$this->db->from('mytable'); 
$query = $this->db->get(); 
$subQuery1 = $this->db->_compile_select(); 

$this->db->_reset_select(); 

// #2 SubQueries no.2 ------------------------------------------- 

$this->db->select('title, content, date'); 
$this->db->from('mytable2'); 
$query = $this->db->get(); 
$subQuery2 = $this->db->_compile_select(); 

$this->db->_reset_select(); 

// #3 Union with Simple Manual Queries -------------------------- 

$this->db->query("select * from ($subQuery1 UNION $subQuery2) as unionTable"); 

// #3 (alternative) Union with another Active Record ------------ 

$this->db->from("($subQuery1 UNION $subQuery2)"); 
$this->db->get(); 

什麼是困惑我是說你在你原來的子查詢get_where條款,你怎麼包含?事情是這樣的:

查詢1個

$this->db->select('Id,title, content, date'); 
$this->db->from('mytable'); 
$query = $this->db->get_where('Boo', array('Id' => $foo['foo_Id']); 
$subQuery1 = $this->db->_compile_select(); 

查詢2

$this->db->select('title, content, date'); 
    $this->db->from('mytable2'); 
    $query = $this->db->get_where('Boo', array('Title' => $foo['foo_Title']) 
    $subQuery2 = $this->db->_compile_select(); 

謝謝。

回答

1

您可以將它們全部寫入其中。你不必這樣。這裏我寫一個例子:

$q = ' 
SELECT userid 
FROM users 
WHERE userid=10 
UNION 
SELECT userid 
FROM users 
WHERE userid=5 
'; 
$result = $this->db->query($q); 
return $result; 
+0

我讀過,做這樣的說法是不這樣做 – bobo2000 2012-04-05 14:06:35

+0

這是簡單明瞭的方式來做到這一點的最好辦法。你能分享一下你讀過的東西嗎? – 2012-04-05 14:16:26

+0

當然,這裏閱讀:[鏈接] http://stackoverflow.com/questions/2040655/union-query-with-codeigniters-active-record-pattern [/ link] – bobo2000 2012-04-05 14:18:31

0

如果沒有很好的文檔記錄,你發現的例子是很難遵循的;我會提醒你反對它。

你的其他選擇包括:

  • 查看
  • 存儲過程
  • 硬編碼查詢

我會建議硬編碼,除非你節省切換數據庫引擎的可能性,正如一位評論者所提到的那樣。

記住,Always Use Gloves