CI如何在另一列查询的选择总和中选择另一列的最后一行

时间:2017-04-24 09:26:17

标签: php mysql codeigniter

+-----+-----+-------+
| PID | Qty | Price |
+-----+-----+-------+
|   1 |   5 |   100 |
|   2 |  10 |   500 |
|   3 |   4 |   300 |
+-----+-----+-------+

$this->db->select("SUM(qty) as total, price as last price");
$this->db->from('table');
$query = $this->db->get();
$result = $query->result();

现在上面的代码将返回与价格一样多的行,

我想只返回一行,其中有总数量和价格的最后一个值

预期产出:

Array (
    [0] => stdClass Object
        (
            [total] => 19
            [last_price] => 300
        )
)

我有一个包含数千行数量和价格的表格,但我想选择列数量的总和,只选择价格的最后一个值,而不是数量和所有价格行的总和,我只想要最后一个价值如何编写我的选择查询?

提前谢谢。

3 个答案:

答案 0 :(得分:2)

你可以这样做: -

$this->db->select("SUM( qty ) AS qty, (SELECT Price FROM  <table name> ORDER BY PID DESC LIMIT 1) AS Price");
$this->db->from('table');

注意: - 而不是<table name>在那里写下您的实际表名。还要注意列名。

答案 1 :(得分:1)

您可以使用此

获得结果

SELECT SUM(qty) As qty, (SELECT Price FROM table price desc limit 1) AS price FROM table price dlimit 1

答案 2 :(得分:1)

试试这个:

SELECT SUM(qty), a.*
FROM products, 
(SELECT price FROM products
ORDER BY pid DESC 
LIMIT 1) a;