使用SQLalchemy我想执行左外连接并过滤掉在连接表中具有匹配项的行.
我正在发送推送通知,所以我有一张Notification桌子.这意味着我还有一个ExpiredDeviceId表来存储不再有效的device_ids.(我不想只删除受影响的通知,因为用户以后可能会重新安装应用程序,此时通知应根据Apple的文档恢复.)
CREATE TABLE Notification (device_id TEXT, time DATETIME);
CREATE TABLE ExpiredDeviceId (device_id TEXT PRIMARY KEY, expiration_time DATETIME);
Run Code Online (Sandbox Code Playgroud)
注意:每个device_id可能有多个通知.每个设备都没有"设备"表.
所以在做的时候SELECT FROM Notification我应该相应地过滤.我可以在SQL中做到这一点:
SELECT * FROM Notification
LEFT OUTER JOIN ExpiredDeviceId
ON Notification.device_id = ExpiredDeviceId.device_id
WHERE expiration_time IS NULL
Run Code Online (Sandbox Code Playgroud)
但是我怎么能在SQLalchemy中做到这一点?
sess.query(
Notification,
ExpiredDeviceId
).outerjoin(
(ExpiredDeviceId, Notification.device_id == ExpiredDeviceId.device_id)
).filter(
???
)
Run Code Online (Sandbox Code Playgroud)
或者我可以用一个device_id NOT IN (SELECT device_id FROM ExpiredDeviceId)子句做到这一点,但这似乎效率低下.
我有一个SQL查询,它在几个表上进行了一系列左连接:
SELECT
<some attributes>
FROM table1 t1
INNER JOIN table2 t2
ON attr = 1 AND attr2 = 1
LEFT JOIN table3 t3
ON t1.Code = t2.Code AND t3.Date_ = t1.Date_
LEFT JOIN tabl4 t4
ON t4.Code = t1.code AND t4.Date_ = t1.Date_
Run Code Online (Sandbox Code Playgroud)
到目前为止,我有:
(sa.select([idc.c.Code])
.select_from(
t1.join(t2, and_(t1.c.attr == 1, t2.c.attr2 = 1))
.join(t3, t3.c.Code == t1.c.Code)))
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何进行加入LEFT JOIN.