delete a record and its FOREIGN key via a sql query

347 Views Asked by At

I want delete an record by 'url' key match in this table:

$sql = "CREATE TABLE IF NOT EXISTS Articls 
        (
            id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,     
            alias INT(10) UNSIGNED NOT NULL,                                 
            title VARCHAR(254) COLLATE utf8_persian_ci NOT NULL,        
            url VARCHAR(2083) COLLATE utf8_persian_ci NOT NULL,                      
            UNIQUE (alias),
            UNIQUE (title),
        )   DEFAULT COLLATE utf8_persian_ci";

but After that I want delete all relative tags name in 'Tags' table too!

 $sql = "CREATE TABLE IF NOT EXISTS Tags (
            id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,  
            alias INT(10) UNSIGNED NOT NULL,    
            name VARCHAR(256) COLLATE utf8_persian_ci NOT NULL, 
            state INT(2) NOT NULL DEFAULT 1, 
            created INT(11) NOT NULL,
            FOREIGN KEY (alias) REFERENCES Articls (alias)      
        ) DEFAULT COLLATE utf8_persian_ci";

Can I do it just with mysql query?

I do it with some php/mysql now:

1-get alias where url = 'my url' in Articls.

2- delete all record in Tags table.

  1. delete target record (where url = 'my url') in 'Articls' table.
1

There are 1 best solutions below

0
On

You should use 2 queries

DELETE FROM Tags
WHERE alias IN (SELECT id FROM Articls WHERE url = 'myurl.com')
;
DELETE FROM Articls WHERE url = 'myurl.com'
;

Or you can use cascade delete.
Instead:

FOREIGN KEY (alias) REFERENCES Articls (alias);

you need:

FOREIGN KEY (alias) REFERENCES Articls (alias) ON DELETE CASCADE

in this case each time when you delete row from Articls appropriate rows at Tags will be automatically deleted.