简体   繁体   English

与3个表相关的SQL COUNT个条目

[英]SQL COUNT entries related to 3 tables

I had this sql statement running for these two tables: tblStations and tblThreads, for counting number of Stations in each thread: 我为这两个表运行了此sql语句:tblStations和tblThreads,用于计算每个线程中Station的数量:

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

and then display tblThread.Name and TotalStationsInThread, for each thread in the system. 然后为系统中的每个线程显示tblThread.Name和TotalStationsInThread。

Now I added another table (tblUsers) in this hierarchy: each thread can have many users, and each user can have many stations. 现在,我在此层次结构中添加了另一个表(tblUsers):每个线程可以有许多用户,并且每个用户可以有许多工作站。 The three tables are related to each other by this: 这三个表通过以下方式相互关联:

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

So I changed my SQL query to this: 因此,我将SQL查询更改为:

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

But now I'm getting this message: "No value given for one or more required parameters." 但是现在我收到此消息:“没有为一个或多个必需参数提供值”。 It's like the database can't connect the tables tblStations with tblThreads via tblUsers... 就像数据库无法通过tblUsers将表tblStation与tblThreads连接起来...

Any help please on how to count the number of stations that are connected to all the users that are connected to each thread?? 关于如何计算与每个线程连接的所有用户连接的站数,有任何帮助吗?

This is the correct answer for MS Access Jet Database Engine: 这是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;

Many thanks for Gordon Linoff for his answer. 非常感谢Gordon Linoff的回答。

You need to include tblUsers in the from clause: 您需要在from子句中包含tblUsers

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM