简体   繁体   English

如何在MySQL中使用空外键查找所有结果?

[英]How can I find all results with a null foreign key in MySQL?

I have 2 tables... meat and potatoes in MySQL. 我有2张桌子... MySQL中的meatpotatoes

meat_id is the primary key for the meat table and there is a meat_id in the potatoes table that links the 2 tables. meat_id对于主键meat表并有一个meat_idpotatoes链接的2代表的表。 I want to find all rows in the potatoes table that don't have a valid meat_id . 我想在potatoes表中查找所有没有有效的meat_id Any ideas? 有任何想法吗?

Using LEFT JOIN/IS NULL: 使用LEFT JOIN / IS NULL:

   SELECT p.*
     FROM POTATOES p
LEFT JOIN MEAT m ON m.meat_id = p.meat_id
    WHERE m.meat_id IS NULL

Using NOT EXISTS: 使用不存在:

SELECT p.*
  FROM POTATOES p
 WHERE NOT EXISTS(SELECT NULL
                    FROM MEAT m
                   WHERE m.meat_id = p.meat_id)

Using NOT IN: 使用NOT IN:

SELECT p.*
  FROM POTATOES p
 WHERE p.meat_id NOT IN (SELECT m.meat_id
                           FROM MEAT m)

Summary 摘要

LEFT JOIN/IS NULL is the best performing option if the column(s) compared in the join can not be NULL . 如果联接中比较的列不能为NULL,则LEFT JOIN / IS NULL是最佳性能选项 If those values can be NULL , then NOT EXISTS or NOT IN perform best . 如果这些值可以为NULL ,则NOT EXISTS或NOT IN的性能最佳

 SELECT *
 FROM potatoes p
 WHERE NOT EXISTS (SELECT 1 from meat m where m.meat_id = p.meat_id)

Do a left join and use having: 进行左连接并使用具有:

SELECT p.potato_id, m.meat_id
FROM potatos p
LEFT JOIN meat m ON p.meat_id = m.meat_id
HAVING m.meat_id IS null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM