与3个表相关的SQL COUNT条目

时间:2013-09-07 15:41:06

标签: sql ms-access count

我为这两个表运行了这个sql语句:tblStations和tblThreads,用于计算每个线程中的站数:

SELECT tblThreads.*, (SELECT COUNT(*) FROM tblStations WHERE tblStations .fldThreadID=tblThreads.fldID) AS TotalStationsInThread FROM tblThreads;

然后显示系统中每个线程的tblThread.Name和TotalStationsInThread。

现在我在此层次结构中添加了另一个表(tblUsers): 每个线程可以有很多用户,每个用户可以拥有多个站点。 这三个表格相互关联:

tblStations.fldUserID=tblUsers.fldID > tblUsers.fldThreadID=tblThreads.fldID.

所以我将SQL查询更改为:

SELECT tblThreads.*, (SELECT COUNT(*) FROM tblStations WHERE tblStations.fldUserID=tblUsers.fldID AND tblUsers.fldThreadID=tblThreads.fldID) AS TotalStationsInThread FROM tblThreads;

但是现在我收到了这样的信息:“没有给出一个或多个必需参数的值。”这就像数据库无法通过tblUsers将表tblStations与tblThreads连接起来......

有关如何计算连接到每个线程的所有用户的站点数量的任何帮助吗?

2 个答案:

答案 0 :(得分:1)

这是MS Access Jet数据库引擎的正确答案:

SELECT tblThreads.*, (SELECT COUNT(tblStations.fldUserID) FROM tblStations INNER JOIN tblUsers ON tblStations.fldUserID = tblUsers.fldID WHERE  tblUsers.fldThreadID = tblThreads.fldID)  AS TotalStationsInThread FROM tblThreads;

非常感谢Gordon Linoff的回答。

答案 1 :(得分:0)

您需要在tblUsers子句中加入from

SELECT tblThreads.*,
       (SELECT COUNT(*)
        FROM tblUsers inner join
             tblStations
             on tblStations.fldUserID = tblUsers.fldID
        WHERE tblUsers.fldThreadID = tblThreads.fldID
       ) AS TotalStationsInThread
FROM tblThreads;