簡體   English   中英

MySQL查找一個表中的記錄,而該表沒有另一表中的列的值

[英]MySQL Find records in one table that has no value of a column in another table

我有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的條目。

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

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

使用相關子查詢

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
    )    

小提琴中的演示

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

演示版

最簡單有效的方法是使用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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM