我有假设的表(为方便使用真实姓名的指数)
表:product_price
id:|产品| valuta |位置|价格
-------------------------------------------------- ----------------
01 |牛奶|欧元|伦敦| 20
02 |牛奶|美元| 波士顿 | 19
03 |牛奶|日元| 波士顿 | 180
04 |苹果|美元| 波士顿 | 200
05 |苹果|美元| Springfild | 210
如何获得这个阵列?
array(<br>
array('id'=>01, 'product'=>milk, 'location'=>'Boston', 'price_USD'=>19, 'price_JPY'=>180),<br>
array('id'=>02, 'product'=>apple, 'location'=>'Boston', 'price_USD'=>200)<br>
);
答案 0 :(得分:0)
您的基本查询可能看起来像
SELECT MIN(id) id,
MIN(location) location,
product,
MIN(CASE WHEN valuta = 'USD' THEN price END) price_usd,
MIN(CASE WHEN valuta = 'JPY' THEN price END) price_jpy
FROM product_price
WHERE location = 'Boston'
GROUP BY product
ORDER BY id
输出:
| ID | LOCATION | PRODUCT | PRICE_USD | PRICE_JPY | --------------------------------------------------- | 2 | Boston | milk | 19 | 180 | | 4 | Boston | apple | 200 | (null) |
这是 SQLFiddle 演示
现在我不是codeigniter专家,但在codeigniter中它可能看起来
$result = $this->db
->select(
'MIN(id) id,
MIN(location) location,
product,
MIN(CASE WHEN valuta = 'USD' THEN price END) price_usd,
MIN(CASE WHEN valuta = 'JPY' THEN price END) price_jpy')
->from('product_price')
->where(array('location' => 'Boston')
->group_by(array('product')
->order_by(array('id')
->get();