简体   繁体   English

如何删除外键为NULL的行?

[英]How can I delete rows where its foreign key is NULL?

I have two tables with names tab1 and tab2 . 我有两个表,分别名为tab1tab2

tab1's p rimary key is price and price is foreign key in tab2 and it is on delete set null. tab1的主rimary key is priceprice is foreign key in tab2并且on delete set null.

When I delete one of primary key from tab1 that exists in tab2 the respective foreign key 当我从tab2中存在的tab1中删除primary key之一时,相应的外键

is set to NULL. 设置为NULL。

Now I want to delete the row from tab2 where their foreign key is null. 现在,我想从tab2中删除其外键为null的行。

I write this query but it does't work. 我写此查询,但它不起作用。

delete from tab2 where price = null.

Please help me in solving it. 请帮我解决。

You can't compare NULL using =. 您不能使用=比较NULL。 You should use IS NULL instead 您应该改用IS NULL

WHERE price IS NULL

From the MySQL Reference Manual MySQL参考手册

The NULL value can be surprising until you get used to it. 在您习惯之前,NULL值可能令人惊讶。 Conceptually, NULL means “a missing unknown value” and it is treated somewhat differently from other values. 从概念上讲,NULL表示“缺少未知值”,并且与其他值的处理方式有所不同。 To test for NULL, you cannot use the arithmetic comparison operators such as =, <, or <>. 要测试NULL,不能使用算术比较运算符,例如=,<或<>。

But if you are already using on delete set null , why not simply change this to on delete cascade and save you the trouble from deleting the rows manually? 但是,如果您已经on delete set null使用on delete set null ,为什么不将其简单地更改为on delete cascade并为您省去手动删除行的麻烦呢?

delete from tab2 where price is null

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

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