我如何将这2个MySQL查询加在一起

时间:2013-06-22 17:07:54

标签: php mysql sql subquery

我有一些产品有很多产品,而且列表会增长

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

An SQLfiddle to test with

作为旁注,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;

答案 2 :(得分: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

答案 3 :(得分:0)

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

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

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

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
; 

此查询已经过测试,对我来说运行正常。