ORDER BY不使用GROUP BY

时间:2014-03-24 08:45:44

标签: php mysql

我已经使用group by和order by编写了sql代码但是在这里顺序不工作可以任何人帮助我

SELECT " . DB_PREFIX . "leaderboard_scores.* , SUM(" . DB_PREFIX . "leaderboard_scores.score) as total_score, " . DB_PREFIX . "customer.firstname, 
        " . DB_PREFIX . "customer.lastname
FROM " . DB_PREFIX . "leaderboard_scores 
JOIN " . DB_PREFIX . "customer ON  " . DB_PREFIX . "leaderboard_scores.philips_store_id = " . DB_PREFIX . "customer.customer_id
GROUP BY " . DB_PREFIX . "leaderboard_scores.phi_store_id
ORDER BY " . DB_PREFIX . "leaderboard_scores.week DESC

此查询工作没有php错误,但给出了中间行而没有给出前几周。周商店使用时间戳

实际查询

SELECT rc_leaderboard_scores.* , SUM(rc_leaderboard_scores.score) 
as total_score, rc_customer.firstname, rc_customer.lastname 
FROM rc_leaderboard_scores 
JOIN rc_customer 
ON rc_leaderboard_scores.phi_store_id = rc_customer.customer_id 
GROUP BY rc_leaderboard_scores.phi_store_id 
ORDER BY rc_leaderboard_scores.week DESC 

1 个答案:

答案 0 :(得分:0)

如果您需要为每个客户返回最后一条记录,则需要一个带有子查询的JOIN,该子查询为每个客户ID返回MAX(周):

SELECT
  rc_leaderboard_scores.*,
  m.total_score,
  rc_customer.firstname,
  rc_customer.lastname 
FROM
  (SELECT   phi_store_id,
            MAX(`week`) as max_week,
            SUM(score) as total_score,
   FROM     rc_leaderboard_scores
   GROUP BY phi_store_id) m
  INNER JOIN
  rc_leaderboard_scores
  ON rc_leaderboard_scores.phi_store_id = m.phi_store_id
     AND rc_leaderboard_scores.`week` = m.max_week
  INNER JOIN
  rc_customer ON m.phi_store_id = rc_customer.customer_id