tags:

views:

27

answers:

3

hi,

i got 2 tables. product and order_items which contain all the products that were bought.

so how do i create a relationship in mysql whereby if a product exists in order_items, restrict users from deleting it from product table??

thanks

A: 

You're looking for a foreign key. Specifically look at the "Restrict" option.

http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html

Stefan Mai
+2  A: 

You can do this with Foreign keys with the InnoDB Engine.

ALTER TABLE order_items ADD FOREIGN KEY (`p_id`) REFERENCES `products` (`p_id`);

The ID on products must be a key (it probably already is the primary key).

If you are not using InnoDB, you cannot enforce this with MySQL, but it must be enforced with your application (check whether a record exists in orders first for example).

So with your tables, you run:

ALTER TABLE `order_item` ADD FOREIGN KEY (`bookid`) REFERENCES `book` (`id`);
tandu
Thanks for writing out the code. ON DELETE RESTRICT is default.
Stefan Mai
Good. That is what you want, right?
tandu
hi i got an error: Category Timestamp Duration Message Line PositionError 10/10/2010 2:21:04 PM 0:00:00.000 MySQL Database Error: Cannot add or update a child row: a foreign key constraint fails (`databasename`.`#sql-248_72`, CONSTRAINT `#sql-248_72_ibfk_1` FOREIGN KEY (`p_id`) REFERENCES `products` (`p_id`)) 1 0
I don't know the table structure that you have. I was just guessing with p_id. Use the real key/column names, obviously, or post your table structure so I can help you out.
tandu
hi pls see above for my table structure
I don't see? I am talking about showing me the contents of SHOW CREATE TABLE for both the products and order items tables.
tandu
i submitted an ans with my my table structure.. saw that??
Oh I see; I was expecting an edit to the main post. Edited my answer to be specific for yours.
tandu
Hi, im still getting the same error.
Are there any rows on order_item with bookid that do not have a matching id on book?
tandu
oh yes. thats the problem.. i deleted those records and now it works. tks tandu!!
A: 

my table structure:

CREATE TABLE `book` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userid` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `description` text NOT NULL,
  `author` varchar(100) NOT NULL,
  `publisher` varchar(100) NOT NULL,
  `edition` int(11) NOT NULL,
  `isbn` varchar(13) NOT NULL,
  `category` varchar(11) NOT NULL,
  `datesubmitted` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8;

CREATE TABLE `order_item` (
  `orderid` int(11) NOT NULL,
  `bookid` int(11) NOT NULL,
  KEY `Foreign` (`bookid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;