我有这个查询,效果很好
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.
所以我一般来说我想获得新的更新条目请上下最大。
如果许多最大投票值相同,则只需选择一个具有最小投票值的值
有什么解决办法吗?
最佳答案
你会想要使用一个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/