[英]How can I find all results with a null foreign key in MySQL?
I have 2 tables... meat
and potatoes
in MySQL. 我有2张桌子... MySQL中的
meat
和potatoes
。
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_id
在potatoes
链接的2代表的表。 I want to find all rows in the potatoes
table that don't have a valid meat_id
. 我想在
potatoes
表中查找所有没有有效的meat_id
。 Any ideas? 有任何想法吗?
SELECT p.*
FROM POTATOES p
LEFT JOIN MEAT m ON m.meat_id = p.meat_id
WHERE m.meat_id IS NULL
SELECT p.*
FROM POTATOES p
WHERE NOT EXISTS(SELECT NULL
FROM MEAT m
WHERE m.meat_id = p.meat_id)
SELECT p.*
FROM POTATOES p
WHERE p.meat_id NOT IN (SELECT m.meat_id
FROM MEAT m)
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.