忽略我“跳过”的记录?

时间:2019-12-20 15:04:15

标签: mysql

我有两个表:tableAtableB

tableA
------
id
...

tableB
------
id
tableA_id
user_id

如果用户没有足够的信息来处理项目,则可以“跳过”该项目;这会向tableB添加一行,其中包含tableA中项的ID及其用户ID。

我想从tableA获取用户没有跳过但其他用户可能跳过的行。

例如:

userA enters the queue
userA is assigned item1
userA skips item1

userB enters the queue
userB is assigned item1
userB skips item1

userA enters the queue
userA is assigned item2

userB enters the queue
userB is assigned item3

userC enters the queue
userC is assigned item1

到目前为止,我有:

SELECT *
FROM tableA
LEFT OUTER JOIN tableB ON tableA.id = tableB.tableA_id
WHERE tableB.user_id IS NULL OR tableB.user_id != %s
GROUP BY tableA.id
;

由于item1不再是user_id,因此任何用户跳过此操作后,它将为所有其他用户返回NULL。这样可以防止其他用户跳过该项目。

我如何完成我想做的事情?

3 个答案:

答案 0 :(得分:2)

尝试一下:

select * from tableA
where tableA.id not in
(select tableB.tableA_id from tableB where tableB.user_id = %s)

答案 1 :(得分:0)

您可以将查询更改为以下内容:

SELECT tableA.*
FROM tableA
LEFT OUTER JOIN (SELECT * FROM tableB WHERE user_Id = %s) tableB ON tableA.id = tableB.tableA_id
WHERE tableB.Id IS NULL

答案 2 :(得分:0)

要从一个表返回行,而该表中没有与另一个表匹配的行,则典型的模式是反联接:

SELECT a.id
  FROM `tableA` a
  LEFT 
  JOIN `tableB` b 
    ON b.tablea_id = a.id
   AND b.user_id   = %s
 WHERE b.user_id IS NULL
 ORDER
    BY a.id

一种查看方式,我们将返回a all 行以及b的所有匹配行。这是外部联接,因此将返回a中没有匹配项的行,以及b中包含所有NULL值的虚拟占位符行。诀窍是WHERE子句中的条件会过滤掉所有具有匹配项的行,而仅保留a中没有匹配项的行。

我们可以使用带有相关子查询的NOT EXISTS来获得等效结果:

SELECT a.id
  FROM `tableA` a
 WHERE NOT EXISTS
       ( SELECT 1
           FROM `tableB` b 
          WHERE b.tablea_id = a.id
            AND b.user_id   = %s
       )
 ORDER
    BY a.id