简体   繁体   中英

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

I have two tables with names tab1 and tab2 .

tab1's p rimary key is price and price is foreign key in tab2 and it is on delete set null.

When I delete one of primary key from tab1 that exists in tab2 the respective foreign key

is set to NULL.

Now I want to delete the row from tab2 where their foreign key is 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 =. You should use IS NULL instead

WHERE price IS NULL

From the MySQL Reference Manual

The NULL value can be surprising until you get used to it. Conceptually, NULL means “a missing unknown value” and it is treated somewhat differently from other values. To test for NULL, you cannot use the arithmetic comparison operators such as =, <, or <>.

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?

delete from tab2 where price is null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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