ORDER查询BY两个变量:sum()和date

时间:2017-10-03 13:50:35

标签: php mysql sql join

我的网站显示了一个图像列表(媒体),人们可以在其中进行投票和投票。我希望能够通过最近投票的来列出图片。

这是我的2张桌子:

媒体

+----+-------+-----------+---------------------+
| id | name  |    url    |        date         |
+----+-------+-----------+---------------------+
|  1 | koala | koala.jpg | 2017-10-03 09:27:19 |
|  2 | ...   | ...       | 2017-10-02 09:27:01 |
|  3 | ...   | ...       | 2017-10-01 09:25:23 |
+----+-------+-----------+---------------------+

+----+----------+-------+---------------------+
| id | media_id | value |        date         |
+----+----------+-------+---------------------+
|  1 |        1 |     1 | 2017-10-03 09:27:19 |
|  2 |        1 |    -1 | 2017-10-03 03:27:19 |
|  3 |        2 |     1 | 2017-10-03 02:27:19 |
+----+----------+-------+---------------------+

到目前为止,我能够通过最受欢迎的方式列出媒体,但我找不到加入medias表并使用medias.date进行排序的方法。

$q = $db->query('SELECT media_id,SUM(value) AS trend FROM votes GROUP BY media_id ORDER BY trend DESC');

while($data = $q->fetch())
{
  echo $data['media_id'].'<br>';
}

任何帮助?

编辑:除了第一个查询之外,我想通过medias.date订购我的媒体。

2 个答案:

答案 0 :(得分:2)

只有JOIN两个表格。

示例:

SELECT rating.trend, medias.date, medias.id
FROM (SELECT media_id, SUM(value) AS trend FROM votes GROUP BY media_id) AS rating
INNER JOIN medias ON medias.id = rating.media_id
ORDER BY rating.trend DESC, medias.date DESC

您还可以添加name表格中的urlmedias列。

答案 1 :(得分:2)

您可以加入表格。使用查询:

SELECT m.id,SUM(v.value) AS trend 
FROM media m 
  JOIN votes v 
    ON m.id=v.media_id 
GROUP BY m.id 
ORDER BY trend DESC, m.date DESC

检查小提琴:http://sqlfiddle.com/#!9/da4455/1/0