Navigate
Home
ArticleWiki
Forum
Journal
Search
Newsletter
Links
Tech News
expertsrt.com
Welcome Guest.
Username:

Password:

Remember me

MySQL DELETE statement
Welcome, Guest. Please login or register.
November 20, 2008, 11:48:34 AM
11306 Posts in 1249 Topics by 501 Members
Latest Member: rosaline
Experts Round Table Network  |  Databases  |  MySQL  |  MySQL DELETE statement « previous next »
Pages: [1]
Author Topic: MySQL DELETE statement  (Read 501 times)
CrYpTiC_MauleR
Site Builder

Offline Offline

Posts: 489



WWW
« on: December 18, 2005, 10:28:03 AM »

I'm not much of an expert on more complex MySQL queries so stumped on this.

I have 2 queries, 1st query deletes a journal entry, 2nd query deletes all the notes associated with that journal entry.

        $sql = 'DELETE FROM `entries` '
             . 'WHERE `entry` = ' . $_POST['entry'] . ' '
             . 'AND `account` = ' . ACCOUNT;

        $sql = 'DELETE FROM `notes` '
             . 'WHERE `entry` = ' . $_POST['entry'] . ' '
             . 'AND `account` = ' . ACCOUNT;

How would I combine both of those into a single query? The only different between them is the table name. The column names are the same for each. Thanks!

Nick
Logged

[x] Fight | www.crypticmauler.com
"You must be
Kevin3NF
Mentor

Offline Offline

Posts: 12


WWW
« Reply #1 on: December 18, 2005, 11:06:54 AM »

I don't know MySQL, but in most relational DBs, if you have a relationship defined between the two tables, you cannot delete the parent records first (unless you have cascade delete functionlaity, in which case you don't need the second statement.

In SQL Server, it would be delete the notes, then delete the entries...Cannot combine the statements, but youcan wrap them in a transaction (and should).
Logged

For the love of Pete...include the version of the software you are using in your question :-)
sajuks
Moderator
*
Offline Offline

Posts: 18


« Reply #2 on: December 18, 2005, 09:09:35 PM »

If ur using INNODB then u could use the "ON DELETE CASCADE"
This will delete any record from child when the record from the parent is deleted.
Theres a good example at
http://www.informit.com/articles/article.asp?p=30875&seqNum=8&rl=1
Logged
sajuks
Moderator
*
Offline Offline

Posts: 18


« Reply #3 on: December 18, 2005, 09:16:18 PM »

Again if ur table doesnt have ant f-k relationships then u could use
DELETE parent, child FROM parent LEFT JOIN child USING (par_id)
WHERE parent.par_id = 1;
Logged
Pages: [1]
« previous next »
    Jump to: