【问题标题】:CI How to select the last row of another column in a select sum of another column queryCI如何在另一列查询的选择总和中选择另一列的最后一行
【发布时间】:2017-04-24 09:26:17
【问题描述】:
+-----+-----+-------+
| 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
        )
)

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

提前谢谢你。

【问题讨论】:

  • 你如何定义最后一行?
  • $this->db->select("SUM(qty) as total, price as last price ORDER BY PID DESC limit 1");
  • @AlivetoDie 以上不起作用..
  • @AlivetoDie 是的,它不起作用
  • @Forward 最后一行是 price 列的最后一个值

标签: php mysql codeigniter


【解决方案1】:

你可以这样做:-

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

注意:- 不要在&lt;table name&gt; 那里写上你的实际表名。还要注意列名。

【讨论】:

  • 很好,谢谢,不知道您可以在 select 语句中放置另一个 SELECT。谢谢!
  • @Charas 很高兴为您提供帮助。:):)
【解决方案2】:

试试这个:

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

【讨论】:

    【解决方案3】:

    你可以用这个得到结果

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

    【讨论】:

      猜你喜欢
      • 2020-03-02
      • 2021-05-25
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2013-12-22
      相关资源
      最近更新 更多