我有两张桌子…mysql中的meatpotatoes
meat_idmeat表的主键,并且meat_id表中有一个potatoes链接这两个表。我想在potatoes表中找到所有没有有效meat_id的行。有什么想法吗?

最佳答案

使用左联接/为空:

   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。如果这些值can be NULL, then NOT EXISTS or NOT IN perform best

10-08 04:44