如何获得社交网络网站每个成员的平均评价

时间:2017-02-19 17:37:38

标签: sql oracle average

所以我有3张桌子:

Member (
  memberId integer,
  name varchar(50)
)

Photo (
  memberId integer,
  photoId integer
)

Like (
  photoId integer,
  memberId integer 
)

对于每个成员,我需要得到他在所有照片中的平均喜欢 如果每张照片至少有一张相似的话,我就可以这样做,但是如果我添加一张没有任何喜欢的照片,它就不会包含在结果中......

感谢您的帮助

编辑: 这是我之前为memberId 201701所做的事情

SELECT AVG(RCOUNT) 
FROM 
(
    SELECT COUNT (*) AS RCOUNT 
    FROM LIKE 
    WHERE photoId IN 
    (
        SELECT photoId 
        FROM PHOTO 
        WHERE memberId = 201701
    ) 
    GROUP BY photoId 
);

3 个答案:

答案 0 :(得分:1)

你也可以使用finner子查询的连接(左边连接照片没有像)

SELECT AVG(T.RCOUNT) 
FROM 
(
        SELECT nvl(count( * ),0) as  RCOUNT 
        FROM PHOTO  as  a
        left  JOINN LIKE as b on a.a.photoId  = b.photoId 
        WHERE a.memberId = 201701
        group by a.photoId

) T 

答案 1 :(得分:0)

这应该可以通过表LIKEPHOTO

之间的外部联接来实现
SELECT AVG(RCOUNT) FROM (
  SELECT COUNT (*) AS RCOUNT 
    FROM PHOTO as AS p
       LEFT OUTER JOIN LIKE as l on p.photoId = l.photoId
   WHERE p.memberId = 201701
   GROUP BY p.photoId );

答案 2 :(得分:0)

我认为你提出了错误的问题。

  1. 如果你想得到Like表中Photo的平均值,你必须像你一样只查询Like表。

  2. 如果你想在Like表中获得Like表中的Photo的平均数,你不必查询Like表,因为Photo表包含所有PhotoId,包括Like表。

  3. 所以,之前的答案如下:

    SELECT AVG(RCOUNT) FROM (
        SELECT COUNT (*) AS RCOUNT 
            FROM PHOTO as AS p
            LEFT OUTER JOIN LIKE as l on p.photoId = l.photoId
        WHERE p.memberId = 201701
    GROUP BY p.photoId );
    

    可以转换如下:

    SELECT AVG(RCOUNT) FROM (
        SELECT COUNT (*) AS RCOUNT 
            FROM PHOTO as AS p
        WHERE p.memberId = 201701
        GROUP BY p.photoId );
    

    这两个查询返回完全相同的结果,因为第一个查询使用外连接。