0

我有一个查询,其中包含一些产品有很多产品并且列表会增长

SELECT pid, link, created_at FROM products ORDER BY timestamp DESC

但我还有另一个表,其中包含一个pidrating字段,它pid是产品表的链接。

SELECT AVG(rating) FROM ratings GROUP BY pid

我该如何查询,以便它会提取如下信息?

products.pid, products.link, products.created_at, AVG(ratings.rating)
4

4 回答 4

1

在 MS-SQL 中,可以将其选为:

SELECT p.pid, 
       p.link, 
       p.created_at, 
       (SELECT AVG(rating) FROM ratings r where r.pid = p.pid) as rating
  FROM products p
 ORDER BY timestamp DESC
于 2013-06-22T17:14:39.030 回答
1

在 MySQL 中,这应该给出你想要的结果;

SELECT p.pid, p.link, p.created_at, AVG(r.rating) rating
FROM products p
LEFT JOIN ratings r
  ON p.pid=r.pid
GROUP BY p.pid;

一个用于测试的 SQLfiddle

附带说明一下,MySQL 很特别,因为它允许您执行不完整的GROUP BY查询,因此如果您想在另一个数据库上运行它(或者可能出于文体原因),查询应该改为;

SELECT p.pid, p.link, p.created_at, AVG(r.rating) rating
FROM products p
LEFT JOIN ratings r
  ON p.pid=r.pid
GROUP BY p.pid, p.link, p.created_at;
于 2013-06-22T17:17:58.250 回答
0
SELECT p.pid, link, created_at, avg_rating
FROM products p
JOIN (SELECT pid, AVG(rating) avg_rating
      FROM ratings
      GROUP BY pid) a
ON p.pid = a.pid
ORDER BY timestamp DESC
于 2013-06-22T17:18:21.200 回答
0

当我使用上面的其他帖子时,它总是向我显示这个错误:

'Unknown column "timestamp" in "order clause"'

我相信时间戳已添加到 products 表中的 created_at 列中。所以,我已经使用了这个列本身的排序。它将从产品表中选择最后一行并用它打印 AVG(rating)。

SELECT products.pid, products.link, products.created_at, AVG(ratings.rating)
FROM products, ratings
WHERE products.pid = ratings.pid
GROUP BY products.pid
ORDER BY products.created_at ASC
; 

这个查询已经过测试并且对我来说工作正常。

于 2013-06-22T18:34:48.920 回答