伙计我在SQL数据库中有三个表。 tblTicketDetail
,tblEngineer
和tblTicket_Engineer
(多对多关系的联结表)。在我的应用程序中发生的情况是,当我生成新票证时,票证被分配给一个,两个或三个(最大)工程师(因此是多对多关系)。
以下是表格的结构:
tblTicketDetail
+----------+---------------+--------+
| TicketID | Desc | Status |
+----------+---------------+--------+
| 1 | Description 1 | 1 |
| 2 | Description 2 | 0 |
| 3 | Description 3 | 1 |
+----------+---------------+--------+
tblEngineer
+------------+-------+
| EngineerID | Name |
+------------+-------+
| 1 | Tom |
| 2 | Harry |
| 3 | John |
+------------+-------+
tblTicket_Engineer
+----------+------------+
| TicketID | EngineerID |
+----------+------------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 3 | 1 |
| 3 | 2 |
+----------+------------+
现在我要做的是COUNT所有TicketID
的{{1}}为status
,EngineerID
应该是特定的(例如1)。
我尝试了这个查询,但它生成两个计数
SELECT (
SELECT COUNT(*) total
FROM tblTicketDetail WHERE Status = 1
) AS count1,
(
SELECT COUNT(*) total
FROM tblTicket_Engineer WHERE EngineerID = 1
) AS count2
在这种情况下(其中EngineerID = 1),查询应该生成2的计数。我应该怎么做呢?
答案 0 :(得分:3)
您需要在子查询上创建联接以获取故障单状态,子查询应如下所示:
SELECT COUNT(*) total
FROM tblTicket_Engineer
INNER JOIN tblTicketDetail ON tblTicketDetail.TicketID = tblTicket_Engineer.TicketID AND tblTicketDetail.Status = 1
WHERE tblTicket_Engineer.EngineerID = 1
答案 1 :(得分:2)
我认为以下代码可以帮助您
SELECT Count(*) FROM
tblTicket inner join tblTicket_Engineer on
(tblTicket.TicketID= tblTicket_Engineer.TicketID)
WHERE tblTicket.Status = '1'
AND tblTicket_Engineer.EngineerID = '1'
答案 2 :(得分:2)
你可以试试这个查询
SELECT COUNT(tblTicketDetail.TicketID) FROM tblTicketDetail
JOIN tblTicket_Engineer ON tblTicket_Engineer.TicketID = tblTicketDetail.TicketID
WHERE tblTicket_Engineer.EngineerID = 1
AND tblTicketDetail.Status = 1
答案 3 :(得分:1)
你可以这样做
SELECT COUNT(*) total
FROM tblTicketDetail a, tblTicket_Engineer b
WHERE a.TicketID = b.TicketID AND a.Status = 1 AND b.EngineerID = 1
答案 4 :(得分:0)
试试这个,这可能会对你有所帮助。
SELECT COUNT(*) total
FROM tblTicketDetail as td, tblTicket_Engineer as te
WHERE td.Status = 1
AND te.EngineerID = 1;
答案 5 :(得分:0)
您可能想要使用JOIN:
SELECT COUNT(*) total
FROM tblTicket NATURAL JOIN tblTicket_Engineer NATURAL JOIN tblEngineer
WHERE Status = 1 AND EngineerID = 1
如果您的数据库引擎不支持多个NATURAL JOIN子句,或者您不想使用它们,您可以采用明确的JOIN
SELECT COUNT(*) total
FROM tblTicket INNER JOIN tblTicket_Engineer ON (TicketID)
INNER JOIN tblEngineer ON (EngineedID)
WHERE Status = 1 AND EngineerID = 1
注意不要在生产环境中使用NATURAL JOIN 。请参阅this post。