SQL order by,group by,having

时间:2012-03-06 14:35:46

标签: php sql group-by sql-order-by

我正在使用数据库来存储列id,候选人,post_time和结果的选举结果。在“计票”期间,结果将被放入数据库中。当有新的更新时,将插入一个新条目。

从这个数据库中,我想创建一个表格,其中包含每个候选人(MAX post_time候选人)的最新结果(GROUP BY),按结果排序(ORDER BY结果)。< / p>

如何将其转换为有效的SQL语句?

(我已经尝试mysql order and groupby但没有成功)

我试过了:

SELECT *, MAX(time_post) 
FROM [database] 
GROUP BY candidate 
HAVING MAX(time_post) = time_post 
ORDER BY result

5 个答案:

答案 0 :(得分:2)

假设您不是每个候选人同时有多个结果,那么下一个应该有效:

select r.candiate, r.result
from results r
inner join (
    select candidate, max(post_time) as ptime
    from results
    group by candidate 
) r2 on r2.candiate=r.candidate and r2.ptime=r.post_time
order by r.result

答案 1 :(得分:0)

请注意,MAX不会选择带有最长时间的记录,但会从任意中选择最大记录。所以

SELECT MAX(a), MAX(b) FROM example

其中exmple包含两个记录a=1, b=2a=4, b=0,将导致a=4, b=2,这不在数据中。您应该只使用每个候选人的最新投票创建视图,然后查询。为了提高性能,使用物化视图可能是明智的。

答案 2 :(得分:0)

所有最新结果的post_time可能相同吗?每个候选人每个post_time也只出现一次吗?

这可以通过使用SELECT语句来实现。您是否有理由在新表格中找到结果?

如果每个候选人每个post_time只出现一次:

SELECT candidate, result
FROM table
WHERE post_time = (SELECT MAX(post_time) FROM table)

如果您想计算候选人在最后一次post_time的表格中出现的次数:

SELECT candidate, count(result) as ResultCount
FROM table
WHERE post_time = (SELECT MAX(post_time) FROM table)
GROUP BY candidate

答案 3 :(得分:0)

根据我的尝试,我认为你应该使用这个

SELECT MAX(post_time) FROM `table` GROUP BY candidate ORDER BY result

但MAX规则只返回一个值,因此我不明白为什么需要ORDER BY。

如果您想要多个结果,请尝试查找TOP语句

答案 4 :(得分:0)

单向(显示结果):

SELECT t.*
FROM tableX AS t
  JOIN
    ( SELECT candidate 
           , MAX(time_post) AS time_post
      FROM tableX
      GROUP BY candidate 
    ) AS m
    ON (m.candidate, m.time_post) = (t.candidate, t.time_post)
ORDER BY t.result

和另一个(没有关系,每个候选人只显示一行):

SELECT t.*
FROM
      ( SELECT DICTINCT candidate
        FROM tableX
      ) AS d
  JOIN 
      tableX AS t
    ON t.PK =                  --- the Primary Key of the table, here
       ( SELECT ti.PK          --- and here
         FROM tableX AS ti
         WHERE ti.candidate = d.candidate
         ORDER ti.time_post DESC
         LIMIT 1
       ) 
ORDER BY t.result