【发布时间】:2013-11-12 14:03:12
【问题描述】:
我正在尝试让 mysql 查询进入 Code Igniter 的 Active Record 语法,但遇到了一些困难。
查询是这个问题的结果:Multiple mysql ORDER BY's for multidimensional ordering/grouping
我尝试自己格式化查询,解决了几个错误,但不确定如何进行。我必须自己将get_compiled_select() 函数添加到DB_active_rec.php,并将_reset_select() 从protected 更改为public 才能让它运行。
建议的查询是:
select
t.id,
t.group,
t.date,
t.comlete
from
YourTable t
left join
(select
m.group,
min(m.date) as mindate,
min(t.complete) as groupcomplete
from
YourTable m) mt on mt.group = t.group
order by
coalesce(mt.groupcomplete, t.complete),
coalesce(mt.mindate, t.date),
t.group,
t.complete,
t.date
我的翻译是这样的(注意原文中没有“where”子句,而“date”实际上是“due”):
// Sub query
$this->db->select('m.group, min(m.due) as mindate, min(t.complete) as groupcomplete');
$this->db->from('task m');
$this->db->where('property', $property);
$subquery = $this->db->get_compiled_select();
$this->db->_reset_select();
// Main query
$this->db->select('*');
$this->db->where('property', $property);
$this->db->from('task t');
$this->db->join('($subquery) mt','mt.group = t.group');
$this->db->order_by('coalesce(mt.groupcomplete, t.complete)');
$this->db->order_by('coalesce(mt.mindate, t.due)');
$this->db->order_by('t.group');
$this->db->order_by('t.complete');
$this->db->order_by('t.due');
$query = $this -> db -> get();
// Return
return $query->result();
不幸的是,这只是抛出一个错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mt ON `mt`.`group` = `t`.`group` WHERE `property` = '7' ORDER BY coalesce(mt.gr' at line 3
CI 报告的查询如下所示:
SELECT * FROM (`task` t) JOIN ($subquery) mt ON `mt`.`group` = `t`.`group` WHERE `property` = '7' ORDER BY coalesce(mt.groupcomplete, `t`.`complete)`, coalesce(mt.mindate, `t`.`date)`, `t`.`due`, `t`.`complete`, `t`.`date`
谁能提供一些关于如何正确格式化的建议?不幸的是,我的 mysql 技能非常简单,所以这正在推动我的能力。我的大部分翻译方法来自 Stack Overflow 上的答案,因为我没有以这种方式组合查询的经验(与子查询)。
【问题讨论】:
-
尝试使用
$this->db->last_query()查看您的查询有什么问题 -
嗨 Drixson,该错误已在报告(如问题底部所述)。我确实坚持了该函数调用,但它对错误报告没有任何影响。我需要在更具体的地方称呼它吗?
-
看到这个
('task' t)我认为它应该像('task') t一样,尝试将t替换为任务 -
如果我的预感是正确的,我遇到了这个问题并且与
$this->db->select('*')有关 -
@altsyset 供将来参考,反引号问题是 CI 中的一个已知错误 - github.com/EllisLab/CodeIgniter/issues/296 Whitespace 修复了它。
标签: php mysql codeigniter