我有以下查询
$query = $this->db->query(
'SELECT ii.json
FROM inventory ii
INNER JOIN
(
SELECT json, MAX(id) as MAX_ID
FROM inventory
GROUP BY business_unit
) group_json ON ii.id = group_json.MAX_ID
INNER JOIN business_units
ON ii.business_unit = business_units.id'
);
return $query->result_array();
我们不得不迁移到MSSQL测试服务器,遗憾的是语法不正确。为了避免将来这种情况,我想将其转换为CodeIgniter类型的查询。
任何人都可以告诉我这个查询在CodeIgniter中会是什么样子,我已经尝试了一些东西,但我没有得到任何接近。
答案 0 :(得分:1)
SELECT ii.json
FROM inventory ii
INNER JOIN
(
SELECT json, MAX(id) as MAX_ID
FROM inventory
GROUP BY business_unit, json --<-- "json" needs to be in GROUP BY
) group_json -- Since it is in SELECT but not
ON ii.id = group_json.MAX_ID -- contained in any aggregate function
INNER JOIN business_units
ON ii.business_unit = business_units.id
如果你在SELECT
任何其他列中使用任何聚合函数(MAX,MIN,AVG,SUM,COUNT),那么该选项中的任何聚合函数都不包含这些函数,必须进入GROUP BY
您的查询的子句。