使用基于 Access 中另一个 table 的计算字段进行查询
Query with a calculated field based on another table in Access
我有两个具有以下值的 Microsoft Access table:
Devices
| N | Desc | O | P |
+------+--------+---+---+
| 3560 | ABC | 0 | 0 | <-
| 3559 | DEF | 0 | 1 |
| 3558 | GHI | 1 | 0 |
| 3557 | JKL | 1 | 0 |
| 3548 | MNO | 0 | 0 | <-
| 3549 | PQR | 0 | 0 | <-
| 3540 | STU | 0 | 0 | <-
Notifications
id | N | Email |
---+------+-------------+
1 | 3559 | a@dom.loc | <-
2 | 3548 | a@dom.loc | <-
3 | 3548 | b@dom.loc |
4 | 3547 | b@dom.loc |
5 | 3549 | b@dom.loc |
我想提取所有 Devices
包含 O = 0
和 P = 0
的记录并添加一个名为 的 计算字段 ]已订阅。仅当 Notifications table 中存在相同的 N
且我作为参数提供的 Email
时,此字段才必须为 True
并且False
否则。
有例如 Email = a@dom.loc
参数(即为此目的在 SQL 中硬编码),那么这应该是所需的结果:
| N | Desc | O | P | Subscribed |
+------+--------+---+---+------------+
| 3560 | ABC | 0 | 0 | False |
| 3548 | MNO | 0 | 0 | True |
| 3549 | PQR | 0 | 0 | False |
| 3540 | STU | 0 | 0 | False |
考虑到这两个 table 将来可能会很大,我如何在 Access 中执行此查询?
可能我错过了子查询 SQL,这个有效:
SELECT Devices.N, Devices.Desc, Devices.O, Devices.P,
(SELECT Count(*) FROM Notifications
WHERE Notifications.N = Devices.N
AND Notifications.Email = "a@dom.loc") > 0 AS Subscribed
FROM Devices
WHERE ((Devices.O=0) AND (Devices.P=0))
编辑:@iDevlop 发表评论后,我能够正确创建 LEFT JOIN 变体,谢谢!
SELECT Devices.N, Devices.Desc, Devices.O, Devices.P, Not IsNull(Id) AS Subscribed
FROM Devices
LEFT JOIN (SELECT Notifications.N, Notifications.Id
FROM Notifications
WHERE (Notifications.Email = "a@dom.loc")) AS qNotif
ON Devices.N = qNotif.N
WHERE ((Devices.O=0) AND (Devices.P=0));
我有两个具有以下值的 Microsoft Access table:
Devices
| N | Desc | O | P |
+------+--------+---+---+
| 3560 | ABC | 0 | 0 | <-
| 3559 | DEF | 0 | 1 |
| 3558 | GHI | 1 | 0 |
| 3557 | JKL | 1 | 0 |
| 3548 | MNO | 0 | 0 | <-
| 3549 | PQR | 0 | 0 | <-
| 3540 | STU | 0 | 0 | <-
Notifications
id | N | Email |
---+------+-------------+
1 | 3559 | a@dom.loc | <-
2 | 3548 | a@dom.loc | <-
3 | 3548 | b@dom.loc |
4 | 3547 | b@dom.loc |
5 | 3549 | b@dom.loc |
我想提取所有 Devices
包含 O = 0
和 P = 0
的记录并添加一个名为 的 计算字段 ]已订阅。仅当 Notifications table 中存在相同的 N
且我作为参数提供的 Email
时,此字段才必须为 True
并且False
否则。
有例如 Email = a@dom.loc
参数(即为此目的在 SQL 中硬编码),那么这应该是所需的结果:
| N | Desc | O | P | Subscribed |
+------+--------+---+---+------------+
| 3560 | ABC | 0 | 0 | False |
| 3548 | MNO | 0 | 0 | True |
| 3549 | PQR | 0 | 0 | False |
| 3540 | STU | 0 | 0 | False |
考虑到这两个 table 将来可能会很大,我如何在 Access 中执行此查询?
可能我错过了子查询 SQL,这个有效:
SELECT Devices.N, Devices.Desc, Devices.O, Devices.P,
(SELECT Count(*) FROM Notifications
WHERE Notifications.N = Devices.N
AND Notifications.Email = "a@dom.loc") > 0 AS Subscribed
FROM Devices
WHERE ((Devices.O=0) AND (Devices.P=0))
编辑:@iDevlop 发表评论后,我能够正确创建 LEFT JOIN 变体,谢谢!
SELECT Devices.N, Devices.Desc, Devices.O, Devices.P, Not IsNull(Id) AS Subscribed
FROM Devices
LEFT JOIN (SELECT Notifications.N, Notifications.Id
FROM Notifications
WHERE (Notifications.Email = "a@dom.loc")) AS qNotif
ON Devices.N = qNotif.N
WHERE ((Devices.O=0) AND (Devices.P=0));