我有一个包含数十万条目的表,我试图使用查询来获取特定receiver_id的结果集,并通过sender_id对它们进行分组。我目前的SQL查询工作正常,但我想知道在语句中使用两个MAX调用是否会有任何潜在的问题。它看起来像这样:我可以安全地在SQL查询中使用两个MAX调用
SELECT MAX(id) as id, sender_id, receiver_id, MAX(date) as date
FROM messages
WHERE receiver_id=5 and belong_to=5
GROUP BY sender_id
表日期如下:
id sender_id receiver_id content date belong_to
-- --------- ----------- ------- ------------------- ---------
1 5 7 test 2013-03-11 10:33:54 7
2 5 7 test 2013-03-11 10:33:54 5
3 13 7 test 2 2013-03-13 12:01:36 7
4 13 7 test 2 2013-03-13 12:01:36 13
5 5 7 test 3 2013-03-14 09:15:37 7
6 5 7 test 3 2013-03-14 09:15:37 5
7 25 5 data1 2013-03-15 11:01:36 5
8 25 5 data1 2013-03-15 11:01:36 25
9 16 5 data2 2013-03-17 09:17:17 5
10 16 5 data2 2013-03-17 09:17:17 16
11 25 5 data3 2013-04-05 09:17:17 5
12 25 5 data3 2013-04-05 09:17:17 16
从我查询的输出是这样的:
id sender_id receiver_id date
-- --------- ----------- -------------------
9 16 5 2013-03-17 09:17:17
11 25 5 2013-04-05 09:17:17
是否有使用该查询的任何问题MAX呼叫?如果是的话,还有什么选择?
不,这很好。但是,要明白,只要在select子句中包含'Receiver_id'而不用'receiver_id'进行分组,就是因为where子句将查询仅限制为'receiver_id'的一个值[5]。如果结果中有多个receiver_id值,您必须也可以用'receiver_id'进行分组,或者不将其包含在结果中 – 2013-05-11 13:22:59
请注意,'receiver_id'将从适合的行中随机选择在该群组之下,因为它不是一个聚合,并且它不通过查询聚合到一个聚合/群组中。 (只有MySQL会让你这么做,所有其他的SQL风格都会阻止这种毫无意义的查询。) – Patashu 2013-05-11 13:23:35
不,使用多个'MAX'聚合肯定是有用的。尽管出于可移植性考虑,您可能希望将“GROUP BY”更改为“GROUP BY sender_id,receiver_id”。 – 2013-05-11 13:23:47