如何获得GROUP BY的最后一项

时间:2017-07-25 12:59:39

标签: mysql sql

我有一张这样的表:

id transaction_id auto_recurring paid_amount package_customerid
37              0              1           0                  4
45             37              1           0                  4
51              0              1           0                  4
57             51              1           0                  4
62              0              1           0                  4
67             62              1           0                  4

package_customer_id = 4有6条记录。现在我想得到4的最后一条记录。在这种情况下,id = 67是我想要的记录。我试试这个SELECT * FROM transactions GROUP BY package_customer_id。但是我得到了package_customer_id = 4的第一条记录。即:id = 4是我获取的结果。如何修改这个sql的id = 67(我想要的记录)?

5 个答案:

答案 0 :(得分:2)

SELECT * FROM transactions WHERE package_customer_id = 4 ORDER BY id DESC LIMIT 1;

那将是我的目标。对不起,但我还没有对它进行过测试,我将其留给您:)

编辑:

别忘了引号" `"在列名称' s :)

检查列名package_customer_idpackage_customerid

答案 1 :(得分:0)

请勿使用group by。使用where

SELECT t.*
FROM transactions t
WHERE t.id = (SELECT MAX(t2.id)
              FROM transactions t2
              WHERE t2.package_customer_id = t.package_customer_id
             );

您可以在外部查询中为您喜欢的任何软件包客户ID进行过滤。

答案 2 :(得分:0)

你可以试试这个。

SELECT temp.* FROM (SELECT * FROM `transactions` WHERE package_customer_id = 4 order by id DESC LIMIT 1 ) AS temp GROUP BY temp.package_customer_id

答案 3 :(得分:-1)

您可以这样使用:

SELECT * FROM transactions WHERE id IN (SELECT MAX(id) FROM transactions GROUP BY package_customerid)

答案 4 :(得分:-1)

尝试此查询

如果您需要GROUP BY子句:使用此查询

SELECT * FROM transactions where GROUP BY package_customerid ORDER BY package_customerid DESC LIMIT 1;

OR 如果您不需要GROUP BY子句:使用此查询

SELECT MAX(id),transaction_id,auto_recurring,paid_amount,package_customerid FROM transactions where package_customerid=4; 

<强>输出:

id transaction_id auto_recurring paid_amount package_customerid
67             62              1           0                  4