mysql - 获取最大值和最小值以及所有值和多个 where 子句

标签 mysql max

我有这个查询,效果很好

  SELECT cm.id ,cm.edited,cm.date_edited,cm.voteup,cm.votedown 
  FROM chat_messages cm 
  WHERE TIMESTAMPDIFF(SECOND,cm.date_edited,'$now') < 10 GROUP BY cm.id

这给我在不到 10 秒内编辑的条目。

但除此之外,我还试图获得 max(voteup)min(votedown)

但不要影响第一个查询的第一个条目。我如何合并才能获得我需要的所有条目?

例子:

如果我收到 3 个新的更新条目。我想让他们得到这 3 个加上 voteup 和 votedown 的最大值。

例子:

    id   edited  date_edited          voteup    votedown
    37      0      2016-03-05 22:13:03    5         0
    38      0      2016-04-02 11:15:00    3         7
    39      0      2016-03-05 22:10:06    10        6
    40      0      2016-03-20 21:40:06    5         0
    41      1      2016-04-20 22:28:59    5         0
    42      1      2016-03-20 21:59:15    0         20
    43      1      2016-04-21 22:20:25    8         0     <---- this new updated

我希望的结果是

    id   edited  date_edited         voteup  votedown  maxup  maxdown
    39      0      2016-03-05 22:10:06    10        6    10     NULL
    42      1      2016-03-20 21:59:15    0         20   NUll   20
    43      1      2016-04-21 22:20:25    8         0    NULL   NULL  

我的$现在时间是2016-04-21 22:20:20

解释:

   -id 39 is having maxup vote i want get it

   -id 42  is having maxdown i want get it

   -id 43 is newly updated in that period of 10 seconds.

所以我一般来说我想获得新的更新条目请上下最大。

如果许多最大投票值相同,则只需选择一个具有最小投票值的值

有什么解决办法吗?

这里 my sqlfiddle example

编辑:哦抱歉我的意思是 id 。现在希望我的问题很清楚 enter image description here

最佳答案

你会想要使用一个UNION语句:

SELECT * FROM (
    select cm.id ,cm.edited,cm.date_edited,cm.voteup,cm.votedown 
        , voteup as maxup, null AS maxdown
    from chat_messages cm
    ORDER BY voteup DESC, votedown
    LIMIT 1
) a
UNION
SELECT * FROM (
    select cm.id ,cm.edited,cm.date_edited,cm.voteup,cm.votedown 
        , null as maxup, votedown AS maxdown
    from chat_messages cm
    ORDER BY votedown DESC, voteup
    LIMIT 1
) b
UNION
SELECT * FROM (
  SELECT cm.id ,cm.edited,cm.date_edited,cm.voteup,cm.votedown 
        , null as maxup, null AS maxdown
  from chat_messages cm
  WHERE TIMESTAMPDIFF(SECOND,cm.date_edited,'2016-04-21 22:20:20') < 10
) c

请注意,我使用了 '2016-04-21 22:20:20',但您需要将 $now 替换回

关于mysql - 获取最大值和最小值以及所有值和多个 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36779684/

相关文章:

php - 从一个数据库表中选择一些数据并插入到同一数据库中的另一个表中

mysql:导入模式而不丢失数据

Python:如何在前 10 个值的列表中找到最大值?

c++ - 在未排序的对数组中查找 K UNIQUE 最大元素

algorithm - 容量为 y、x*y 项目的 x 箱子,最大化总分,其中每个(项目,箱子)对都有一个相关联的分数

c# - 我的 SQL 插入格式有什么问题,c# 没有执行它?

添加模块后的 Android Studio ClassNotFoundException : com. mysql.jdbc.Driver

php - 如果字段不存在,则SQL插入行

excel - 计算系列中的最大值时出错

Python Dataframe - 获取特定数字与列值之间的最大值