MySQL查找一个表中的记录,而该表没有另一表中的列的值

时间:2018-10-18 13:24:02

标签: mysql

我有table1,其中包含列(简体):

+-------------------------+
| id | user_id | username |
+----+---------+----------+
|  1 |     123 | peter    |
|  2 |     234 | john     |
+-------------------------+

和表2,其中包含列(简体):

+----------------------------------+
| id | user_id | checklist_item_id |
+----+---------+-------------------+
|  1 |     123 |               110 |
|  2 |     123 |               111 |
|  3 |     123 |               112 |
|  4 |     234 |               110 |
|  5 |     234 |               112 |
+----------------------------------+

如上所示,表1中user_id的每个条目都有该user_id的多个条目以及多个checklist_item_ids。

我有兴趣返回仅第二张表中没有checklist_item_id = 111条目的记录。查询必须仅返回:

+---------+
| user_id |
+---------+
|     234 |
+---------+

作为具有user_id 123的用户,请在表2中具有一个checklist_item_id为111的条目。

3 个答案:

答案 0 :(得分:3)

您可以使用子查询,例如:

SELECT *
FROM table1
WHERE user_id NOT IN
    (SELECT user_id
     FROM table2
     WHERE checklist_item_id = 111)

答案 1 :(得分:2)

使用相关子查询

select t1.* from  table1 t1 where t1.user_id not in
( select user_id from table2 t2
   where t2.user_id=t1.user_id
   and checklist_item_id=111
)

或使用not exist效率要高

select t1.* from table1 t1 where not exists
    ( select 1 from table2 t2  where t2.user_id=t1.user_id and 
    checklist_item_id=111
    )    

DEMO in Fiddle

id  userid  itemid
4   234     110
5   234     112

如果您只需要一个ID,那么它将是

select distinct t1.userid from  t1 where not exists
    ( select 1 from t1 t2  where t2.userid=t1.userid and 
    itemid=111
    )    

输出

userid
  234

Demo

答案 2 :(得分:1)

最简单有效的方法是使用LEFT JOIN,并过滤掉checklist_item_id = 111没有匹配记录的那些行

SELECT DISTINCT t1.user_id 
FROM table1 AS t1 
LEFT JOIN table2 AS t2 ON t2.user_id = t1.user_id AND 
                          t2.checklist_item_id = 111 
WHERE t2.user_id IS NULL 
相关问题