关于嵌套查询和NATURAL JOIN的SQL查询

时间:2012-01-10 21:21:12

标签: sql join

我有三张桌子。 第一个表是活动,第二个是成员,最后一个是消息。 活动有一个名为Members_ID的外键,主键是Activity_ID。 成员的主键是Members_ID。 消息记录了Activity_ID和Members_ID。 我想搜索活动NATURAL JOIN会员,我需要一个新的列数 消息的message_ID,其中Activity_ID是相同的。

NATURAL JOIN:

SELECT*
    FROM Activities 
        NATURAL JOIN Members 
    WHERE Activities.Members_ID = Members.Members_ID;

COUNT(MESSAGE_ID):

SELECT COUNT(message_ID) 
    FROM Message 
    WHERE Activity_ID = 123;

问题是: 如何一起搜索上述两件事? 我希望有一个表有活动NATURAL JOIN成员具有相同的Activities.Members_ID 和表Message中的COUNT(message_ID)的虚拟列。

3 个答案:

答案 0 :(得分:1)

WITH MessageTallies 
     AS
     (
      SELECT Activity_ID, COUNT(message_ID) AS tally
        FROM Message
       GROUP 
          BY Activity_ID
     )
SELECT *
  FROM Activities 
       NATURAL JOIN Members 
       NATURAL JOIN MessageTallies
UNION CORRESPONDING
SELECT *, 0 AS tally
  FROM Activities 
       NATURAL JOIN Members 
 WHERE Activity_ID NOT IN (SELECT Activity_ID FROM MessageTallies):

答案 1 :(得分:0)

SELECT a.Activity_ID, a.col1, a.col2, ..., a.colx, COUNT(mg.message_ID)
    FROM Activities a
        INNER JOIN Members m
            ON a.Members_ID = m.Members_ID
        INNER JOIN Message mg
            ON a.Activity_id = m.Activity_ID 
    GROUP BY a.Activity_ID, a.col1, a.col2, ..., a.colx;

答案 2 :(得分:0)

也许您希望使用相关的子查询,如下所示:

SELECT *, (SELECT COUNT(message_ID) FROM Message WHERE Activity_ID = a.Activity_ID AND Members_ID = m.Members_ID) AS Message_Count
    FROM Activities AS a
        NATURAL JOIN Members AS m
    WHERE a.Members_ID = m.Members_ID;

但是,我会避免使用自然连接语法:

SELECT *, (SELECT COUNT(message_ID) FROM Message WHERE Activity_ID = a.Activity_ID AND Members_ID = m.Members_ID) AS Message_Count
    FROM Activities AS a
        JOIN Members AS m on a.Members_ID = m.Members_ID;