的MySQL>在profile_zipcodes中有2个额外的行(86321和28034),为什么我的第三个查询找不到它们?
SELECT zipcode from profile_zipcodes;
+---------+
| zipcode |
+---------+
| 01971 |
| 02110 |
| 02119 |
| 02124 |
| 02180 |
| 07086 |
| 07087 |
| 10008 |
| 10019 |
| 10021 |
| 10022 |
| 10024 |
| 10025 |
| 10095 |
| 10098 |
| 10099 |
| 10110 |
| 10112 |
| 10118 |
| 10131 |
| 10152 |
| 10157 |
| 10158 |
| 10159 |
| 10160 |
| 10161 |
| 10162 |
| 10166 |
| 10174 |
| 28034 |
| 33306 |
| 33319 |
| 50301 |
| 62334 |
| 63031 |
| 63131 |
| 63138 |
| 63141 |
| 63366 |
| 63376 |
| 67002 |
| 86321 |
+---------+
42 rows in set
的MySQL>
SELECT DISTINCT zip FROM profile_stats;
+-------+
| zip |
+-------+
| NULL |
| 01971 |
| 02110 |
| 02124 |
| 02180 |
| 07086 |
| 07087 |
| 10008 |
| 10019 |
| 10021 |
| 10022 |
| 10024 |
| 10025 |
| 10095 |
| 10098 |
| 10099 |
| 10110 |
| 10112 |
| 10118 |
| 10131 |
| 10152 |
| 10157 |
| 10158 |
| 10159 |
| 10160 |
| 10161 |
| 10162 |
| 10166 |
| 10174 |
| 33306 |
| 33319 |
| 50301 |
| 62334 |
| 63031 |
| 63131 |
| 63138 |
| 63141 |
| 63366 |
| 63376 |
| 67002 |
+-------+
40 rows in set (0.00 sec)
的MySQL>
SELECT * FROM profile_zipcodes WHERE profile_zipcodes.zipcode NOT IN
(SELECT DISTINCT zip FROM profile_stats);
Empty set (0.00 sec)
我的php代码实际运行此查询:
DELETE FROM profile_zipcodes WHERE profile_zipcodes.zipcode NOT IN (SELECT DISTINCT zip FROM profile_stats)
每当用户更改他们的邮政编码或删除他们的个人资料,并且工作正常时,突然我开始注意到没有附加配置文件的邮政编码保留在动态更新的下拉框中,并且调试显示查询仍然存在运行,但旧的拉链仍然存在,测试显示一个措辞相同的SELECT没有找到孤儿拉链 - 它确实工作了一段时间,然后停止了?
答案 0 :(得分:0)
您的profile_stats
表在zip
列中包含NULL值,而使用IN子句的此查询将按预期工作:
DELETE FROM profile_zipcodes
WHERE
profile_zipcodes.zipcode IN (SELECT DISTINCT zip FROM profile_stats)
使用NOT IN
可能有点棘手(请参阅此question,它是关于SQL Sever的,但问题是相同的。)
你可以试试这个:
DELETE FROM profile_zipcodes
WHERE
profile_zipcodes.zipcode NOT IN (SELECT DISTINCT zip
FROM profile_stats
WHERE zip IS NOT NULL)