加入mysql连接两个表MAX(值)

时间:2014-12-05 09:32:01

标签: mysql sql select group-by sum

my question is how to get max share by news id where created_at is today?

尝试     SELECT Max(shares.id),facebook FROM Shares GROUP BY shares.id ORDER BY facebook DESC LIMIT 20;

select * from shares;

+-------+----------+
| id    | facebook |
+-------+----------+
| 1     |      584 |
| 1     |      610 |
| 2     |      354 |
| 2     |      360 |
| 2     |      467 |
| 1     |     1324 |
| 2     |      924 |
+-------+----------+

select * from news;

+----+-------------------------------+------------+
| id | url_address                   | created_at |
+----+-------------------------------+------------+
|  1 | http://www.google.com         | 1417496667 |
|  2 | http://www.facebook.com       | 1417491832 |
+----+-------------------------------+------------+

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT s.id, SUM(s.facebook)
FROM shares s 
INNER JOIN news n ON s.id = n.id 
WHERE n.created_at = UNIX_TIMESTAMP(CURRENT_DATE()) 
GROUP BY s.id 
ORDER BY SUM(s.facebook) DESC 
LIMIT 20;