我有两个表notifications
和archived_notifications
。
通知
id | title | caption | user_id
已归档的通知
notification_id | user_id
如果我要从notifications
表中没有像archived_notifications
这样的行的notification_id = notification.id | user_id = notification.user_id
表中获取行,SQL请求应该如何显示。
现在我有一些这样的
cursor.execute("SELECT * FROM notifications AS n WHERE "
"({}=%s AND (SELECT COUNT(*) FROM archvies WHERE {}=n.id AND {}=%s) = 0) "
"OR "
"({}=%s AND (SELECT COUNT(*) FROM archvies WHERE {}=n.id AND {}=%s) = 0) "
"ORDER by id DESC LIMIT %s OFFSET %s"
.format(Keys.USER_ID, Keys.NOTIFICATION_ID, Keys.USER_ID, Keys.DIRECTION, Keys.NOTIFICATION_ID,
Keys.USER_ID),
[str(user_id), str(user_id), NotificationsClasses.GLOBAL, str(user_id), int(limit), int(offset)])
答案 0 :(得分:1)
通常,您可以使用NOT IN vs. NOT EXISTS vs. LEFT JOIN子句中的任何一个。具体来说,您似乎还有许多其他不清楚的条件,例如 direction 处理和未知 Keys 变量的列名的字符串格式。
以下显示了NOT EXISTS
选项,并尝试翻译您当前的代码。调整以适应实际需求:
sql = '''SELECT * FROM notifications AS n
WHERE n.user_id = %s
AND NOT EXISTS
(SELECT 1 FROM archives a
WHERE a.user_id = %s
AND n.id = a.notification_id)
ORDER by n.id DESC
LIMIT %s
OFFSET %s
'''
cursor.execute(sql, [str(user_id), NotificationsClasses.GLOBAL, int(limit), int(offset)])