SQL:选择查询

时间:2017-02-21 04:28:38

标签: sql oracle

我有这些表格:

  • 会员(IdMember,name,nbFollower)
  • 追随者(IdMember,IdFollower,日期)
  • 朋友(IdMember,IdFriend)
  • 照片(IdPhoto,datePhoto,IdMember)
  • 评论(IdPhoto,IdMember,no,content)
  • 喜欢(IdPhoto,IdMember)

是会员在照片上撰写的评论顺序

我想选择在同一张照片上留下3条以上评论的会员姓名。

我做了这个,但它不起作用:

SELECT name 
FROM MEMBER M, COMMENT C, PHOTO P
WHERE M.IdMember = C.IdMember = P.IdMember
  AND M.IdMember IN (SELECT IdMember 
                     FROM COMMENT
                     GROUP BY IdMember
                     HAVING COUNT(no) >= 3)

如何更改查询?

2 个答案:

答案 0 :(得分:1)

您的查询已关闭,但您需要在Comment表格中 成员合并照片。试试这个:

SELECT name FROM MEMBER M, COMMENT C, PHOTO P
WHERE M.IdMember = C.IdMember = P.IdMember
AND M.IdMember IN
(
    SELECT IdMember
    FROM Comment
    GROUP BY IdMember, IdPhoto
    HAVING COUNT(*) >= 3
)

但实际上我宁愿在任何地方使用显式连接来编写此查询:

SELECT name
FROM MEMBER m
INNER JOIN COMMENT c1
    ON m.IdMember = c1.IdMember
INNER JOIN PHOTO p
    ON c1.IdMember = p.IdMember
INNER JOIN
(
    SELECT IdMember
    FROM Comment
    GROUP BY IdMember, IdPhoto
    HAVING COUNT(*) >= 3
) c2
    ON c1.IdMember = c2.IdMember

答案 1 :(得分:0)

在这种情况下,您不需要加入Photo表,因为您在该表中使用的唯一列是IdPhoto,并且您已在Comment表中拥有该信息。< / p>

您也可以直接将子查询加入Member表,而不再使Comment表再次出现。

如前所述,您还必须在group by子句中添加IdPhoto,以计算相同照片 同一会员的帖子数量

试试这个:

SELECT DISTINCT M.name
    FROM MEMBER M, (SELECT IdMember 
                 FROM COMMENT
                 GROUP BY IdMember, IdPhoto
                 HAVING COUNT(no) >= 3) C
    WHERE M.IdMember = C.IdMember;

或使用ANSI语法:

SELECT DISTINCT M.name
    FROM MEMBER M
      INNER JOIN (SELECT IdMember 
                 FROM COMMENT
                 GROUP BY IdMember, IdPhoto
                 HAVING COUNT(no) >= 3) C
    ON M.IdMember = C.IdMember;