我使用SUM来添加其中一个字段,但对于其他字段,我希望这些字段来自最新条目。
当前查询:
public class Contact implements Comparable<Contact> {
public int compareTo(Contact o) {
return name.compareToIgnoreCase(o.getName());
}
}
当前结果:
SELECT cu.*,
SUM(cu.use_count) AS total_use_count
FROM coupons_used cu
GROUP BY cu.coupon_id;
该时间戳来自第一个条目,我希望它来自最后一个。我尝试添加Array
(
[0] => stdClass Object
(
[id] => 1
[timestamp] => 2015-05-08 04:52:31
[coupon_id] => 133
[user_id] => 104
[use_count] => 1
[redemption_code] => 123412341234
[total_use_count] => 2
)
)
ORDER BY cu.timestamp
和ASC
,但我得到的结果相同。 DESC
需要按原样保留,但如何从最后一个条目中获取其余字段(当然每个分组)?
答案 0 :(得分:4)
如果(coupon_id,timestamp)
元组是唯一的(也就是说,如果我们保证给定coupon_id没有两个(或更多)具有相同timestamp
值的行,那么至少对于& #34;最新&#34;时间戳)....
SELECT c.id
, c.timestamp
, c.coupon_id
, c.user_id
, c.use_count
, c.redemption_code
, m.total_use_count
FROM ( SELECT MAX(mt.timestamp) AS latest_timestamp
, SUM(mt.use_count) AS total_use_count
, mt.coupon_id
FROM coupons_used mt
GROUP BY mt.coupon_id
) m
JOIN coupons_uses c
ON c.coupon_id = m.coupon_id
AND c.timestamp = m.latest_timestamp
如果(coupon_id,timestamp)
不是唯一的;如果给定coupon_id可能有两行具有相同的时间戳,并且如果我们想为每个coupon_id只返回一行...
我们可以使用GROUP BY
的MySQL扩展并添加到查询的末尾:
GROUP BY c.coupon_id
答案 1 :(得分:2)
使用GROUP BY
时,您返回的列应为以下两种类别之一:
GROUP BY
列表的列。MySql通过让您将任何列放在选择列表中来放宽此限制,但这可以理解引擎可以随机选择组中的任何行来为您提供值列。
如果您想要最后一个时间戳,请在其上添加MAX
功能:
SELECT
coupon_id
, SUM(cu.use_count) AS total_use_count
, MAX(cu.timestamp) AS timestamp
FROM coupons_used cu
GROUP BY cu.coupon_id;
答案 2 :(得分:1)
要获得总和,请执行此操作:
SELECT SUM(use_count) AS total_use_count, coupon_id
FROM coupons_used
GROUP BY coupon_id
但是,要获得每个coupon_id的最新条目,请执行此操作。
SELECT c.*
FROM coupon_id AS c
JOIN ( SELECT MAX(id) AS id
FROM coupon_id
GROUP BY coupon_id
) m ON c.id = m.id
内部SELECT获取一个表,其中包含行的id号,这些行是每个coupon_id的最新条目。然后将其连接到主表,从主表中拉出细节。
最后,你必须加入所有这些,每个coupon_id获得一行,总和和最新。
SELECT c.*, a.total_use_count
FROM coupon_id c
JOIN ( SELECT MAX(id) AS id
FROM coupon_id
GROUP BY coupon_id
) m ON c.id = m.id
JOIN (
SELECT SUM(use_count) AS total_use_count, coupon_id
FROM coupons_used
GROUP BY coupon_id
) a ON a.coupon_id = c.coupon_id
您尝试使用GROUP BY的方式使用了标准GROUP BY的麻烦的MySQL扩展。这就是错误排回来的原因。您可以阅读此内容以获取更多信息。 http://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html