Jump to content

Delete from multiple tables


maxat

Recommended Posts

Hi, I am new in mysql and having problem with deleting rows from multiple tables.

I have 3 tables

1. table users
us_id <- primary key

2. table items

  od_id <- primary key
  pd_id <- primary key
  us_id <- primary key
  it_qty

3.table orders

od_id <- primary key


In table "items" all are foreign keys from another tables except it_qty.
The problem is when I delete user from table "user", I want delete all his records from "items" and "order" tables. My tables are in MyIsam. so far I couldn't get any valid query.
Please help me with this query. Thanks in advance.
Link to comment
Share on other sites

Try the following
[code]
DELETE
u,i,o
FROM
users AS u
LEFT JOIN
items AS i
ON u.us_id=i.us_id
LEFT JOIN
orders AS o
ON i.od_id=o.od_id
WHERE u.us_id = $usrID
[/code]

[url=http://dev.mysql.com/doc/refman/4.1/en/delete.html]Delete Syntax[/url]
Link to comment
Share on other sites

MYSQL 4.0 and MYSQL 4.1 or higher deal with aliases in multi-table deletes differently. To avoid problems try this query which doesn't use aliases
[code]
DELETE
users,items,orders
FROM
users
LEFT JOIN
items
ON users.us_id=items.us_id
LEFT JOIN
orders
ON items.od_id=orders.od_id
WHERE users.us_id = $usrID
[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.