如何从数据库中获取有条件的行-另一个表中存在另一个?

时间:2019-06-26 16:51:10

标签: sql postgresql psycopg2

我有两个表notificationsarchived_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)])

1 个答案:

答案 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)])