2012-04-05 88 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