Mysql检索两个列作为一个独特或分组

时间:2016-03-19 16:20:22

标签: mysql group-by union

我被一个mysql查询难倒。我试图从按日期排序的两列中恢复所有唯一值。这是我的表:

from                to               body      created_on
+55555555555        +22222222222     hello     2015-03-20 01:00:00
+11111111111        +33333333333     hello     2015-03-21 01:00:00
+33333333333        +44444444444     hello     2015-03-18 01:00:00
+66666666666        +11111111111     hello     2015-03-12 01:00:00
+11111111111        +77777777777     hello     2015-03-05 01:00:00

基本上它是一个存储短信的表,我想将最近有100个条目的电话号码拉回到短信表中。所以像这样:

number
+11111111111
+77777777777
+66666666666
+22222222222
+33333333333

另一个要求是我不会拉回电话号码+4444444444和+555555555555,因为它们是管理员号码。这些数字也应按日期排序。

这是我到目前为止所做的:

SELECT `from` as num, created_at FROM sms WHERE `from` NOT IN (+4444444444, +5555555555)
GROUP BY num
UNION
SELECT `to` as num, created_at FROM sms WHERE `to` NOT IN (+4444444444, +5555555555)
GROUP BY num
ORDER BY created_at

我知道我很接近,但它带回了我不想要的重复。

1 个答案:

答案 0 :(得分:0)

您最初可以在MAX操作的两个查询中应用UNION,以便获得每个号码的最新日期。再次将它应用于整个集合,并按日期降序排列,并使用LIMIT子句获取最近的100个数字:

SELECT num, MAX(created_at) AS created_at
FROM (
  SELECT `from` as num, MAX(created_at) AS created_at
  FROM sms 
  WHERE `from` NOT IN (+4444444444, +5555555555)
  GROUP BY num

  UNION

  SELECT `to` as num, MAX(created_at) AS created_at
  FROM sms 
  WHERE `to` NOT IN (+4444444444, +5555555555)
  GROUP BY num) AS t
GROUP BY number
ORDER BY created_at DESC LIMIT 100