使用基于Access中另一个表的计算字段进行查询



我有两个Microsoft Access表,其值如下:

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   |

我想提取具有O = 0P = 0的所有Devices记录,并添加一个名为Subscribed计算字段。仅当Notifications表中存在相同的NEmail为我提供的参数时,此字段必须为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      |

考虑到这两个表将来可能会很大,我如何在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));

相关内容

  • 没有找到相关文章

最新更新