MySQL Help
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me
Go Back   Dev Shed ForumsDatabasesMySQL Help

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
Stop making mediocre tutorials.The best tutorials are video! Camtasia Studio makes it easy to create engaging, buzz-building screen videos at any size, in any popular format. Download the free trial!
  #1  
Old May 4th, 2008, 11:07 AM
kriskd kriskd is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2007
Posts: 45 kriskd User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 16 h 19 m 44 sec
Reputation Power: 2
Help with Foreign Key

I'm brand new to MySql so please be patient with me as I learn from all you experts!

I have two tables: order_master and order_detail.

order_master contains a primary key of 'id' and order_detail has a field of 'order_id" which should contain the same value as 'id' in order_master.

I don't know how to recreate the create table query (if someone could tell me, that would be great!), but here are the results from describing my tables:
Code:
describe order_master;
+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| id            | int(12)      | NO   | PRI | NULL    | auto_increment |
| order_date    | datetime     | YES  |     | NULL    |                |
| ship_date     | datetime     | YES  |     | NULL    |                |
| customer_name | varchar(40)  | NO   |     |         |                |
| address       | varchar(100) | NO   |     |         |                |
| item_total    | float(10,2)  | NO   |     |         |                |
| total_amt_due | float(10,2)  | NO   |     |         |                |
+---------------+--------------+------+-----+---------+----------------+

and order_detail:
Code:
describe order_detail;
+----------------+-------------+------+-----+---------+----------------+
| Field          | Type        | Null | Key | Default | Extra          |
+----------------+-------------+------+-----+---------+----------------+
| order_id       | int(12)     | NO   | MUL | NULL    | auto_increment |
| item_name      | varchar(20) | NO   |     |         |                |
| quantity       | int(6)      | NO   |     |         |                |
| price_per_unit | float(10,2) | NO   |     |         |                |
+----------------+-------------+------+-----+---------+----------------+


Here is the mysql command to insert data into the order_master table and it works great:
Code:
mysql_query("INSERT INTO order_master (order_date, customer_name, address, item_total, total_amt_due) " . "VALUES ('$order_date','$customer_name', '$address', '$item_total', '$total_amt_due')", $db);


I'm getting a 'Cannot add or update a child row: a foreign key constraint fails' error when trying to insert into the order_detail table though. Here is my mysql commend for that:

Code:
mysql_query("INSERT INTO order_detail (item_name, quantity, price_per_unit) " . "VALUES ('calendar', '$calqty', '10')", $db);


Can someone spot my (hopefully) simple error?

Reply With Quote
  #2  
Old May 4th, 2008, 11:28 AM
pabloj's Avatar
pabloj pabloj is offline
Modding: Oracle MsSQL Firebird
Dev Shed God 5th Plane (7000 - 7499 posts)
 
Join Date: Jun 2001
Location: Outside US
Posts: 7,395 pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level) 
Time spent in forums: 2 Months 2 Weeks 4 h 48 m 59 sec
Reputation Power: 255
There is a small trick, a function that retrieves the last autoincrement value assigned by the database (because your order_master.id is an autoincrement field) and lets you reuse that.
See this small example
Code:
mysql> use test;
Database changed
mysql> CREATE TABLE `test`.`order_header` (
    ->   `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
    ->   `order_date` DATETIME NOT NULL,
    ->   PRIMARY KEY (`id`)
    -> )
    -> ENGINE = InnoDB;
Query OK, 0 rows affected (0.05 sec)

mysql> CREATE TABLE `test`.`order_details` (
    ->   `order_id` INTEGER UNSIGNED NOT NULL,
    ->   `item_name` VARCHAR(45) NOT NULL,
    ->   `quantity` INTEGER UNSIGNED NOT NULL,
    ->   PRIMARY KEY (`order_id`, `item_name`)
    -> )
    -> ENGINE = InnoDB;
Query OK, 0 rows affected (0.05 sec)
mysql> ALTER TABLE `test`.`order_details` ADD CONSTRAINT `FK_order_details_1` FO
REIGN KEY `FK_order_details_1` (`order_id`)
    ->     REFERENCES `order_header` (`id`)
    ->     ON DELETE RESTRICT
    ->     ON UPDATE RESTRICT;
Query OK, 0 rows affected (0.08 sec)
Records: 0  Duplicates: 0  Warnings: 0
mysql> insert into order_header(id, order_date) values (NULL, now());
Query OK, 1 row affected (0.00 sec)

mysql> select * from order_header;
+----+---------------------+
| id | order_date          |
+----+---------------------+
|  1 | 2008-05-04 18:23:06 |
+----+---------------------+
1 row in set (0.00 sec)
mysql> insert into order_details (order_id, item_name, quantity) values (last_in
sert_id(), 'an item', 6);
Query OK, 1 row affected (0.02 sec)

mysql> select * from order_details;
+----------+-----------+----------+
| order_id | item_name | quantity |
+----------+-----------+----------+
|        1 | an item   |        6 |
+----------+-----------+----------+
1 row in set (0.00 sec)

mysql>
Do you see how last_insert_id() works?
Note that both inserts should be wrapped inside a transaction (but this is another story).

Reply With Quote
  #3  
Old May 4th, 2008, 01:50 PM
kriskd kriskd is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2007
Posts: 45 kriskd User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 16 h 19 m 44 sec
Reputation Power: 2
Thanks! I think I figured it out.

I used mysql_insert_id() versus last_insert_id() -- are they pretty much the same thing?

And for such a simple application, was I over thinking the need for foreign keys? Once I removed that relationship, I didn't get that error anymore. I see in your example you still are using foreign keys...? Let me know your thoughts and thanks for helping a newbie!

Reply With Quote
  #4  
Old May 4th, 2008, 02:32 PM
pabloj's Avatar
pabloj pabloj is offline
Modding: Oracle MsSQL Firebird
Dev Shed God 5th Plane (7000 - 7499 posts)
 
Join Date: Jun 2001
Location: Outside US
Posts: 7,395 pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level)pabloj User rank is Captain (20000 - 30000 Reputation Level) 
Time spent in forums: 2 Months 2 Weeks 4 h 48 m 59 sec
Reputation Power: 255
Quote:
Originally Posted by kriskd
...
I used mysql_insert_id() versus last_insert_id() -- are they pretty much the same thing?
Yes they are, one is for Php the other straight SQL, infact my example doesn't use Php at all.
Quote:
Originally Posted by kriskd
And for such a simple application, was I over thinking the need for foreign keys? Once I removed that relationship, I didn't get that error anymore. I see in your example you still are using foreign keys...? Let me know your thoughts and thanks for helping a newbie!
I'd use them anyway. If you do the two inserts properly you won't get any errors and will have data integrity guaranteed.

Reply With Quote
  #5  
Old May 4th, 2008, 02:58 PM
kriskd kriskd is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2007
Posts: 45 kriskd User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 16 h 19 m 44 sec
Reputation Power: 2
Thanks again... turns out I wasn't quite using mysql_insert_id() correctly, but I figured that out and the order ids between tables match like they should!!

I also reapplied the foreign keys (recall I had removed them) and this time made them RESTRICT per your example instead of CASCADE which caused foreign key errors. If I may ask of you, could you enlighten me as to why RESTRICT works and CASCADE doesn't?

Reply With Quote
Reply

Viewing: Dev Shed ForumsDatabasesMySQL Help > Help with Foreign Key


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

 Free IT White Papers!
 
Accelerating Trading Partner Performance
One in five. That's how many partner transactions have at least one error. That is an amazing statistic, particularly given the extraordinary leaps in innovation across the global supply chain during the past two decades. Download this white paper to learn more.

 
Competing on Analytics
This Tech Analysis is designed to help identify characteristics shared by analytics competitors, and includes information about 32 organizations that have made a commitment to quantitative, fact-based analysis.

 
Cost Effective Scaling with Virtualization and Coyote Point Systems
An overview of the industry trend toward virtualization, how server consolidation has increased the importance of application uptime and the steps being taken to integrate load balancing technology with virtualized servers.

 
Five Checkpoints to Implementing IP Telephony
Implementation planning for IP PBX software and IP telephony has become vital as businesses replace discontinued legacy PBX phone systems. This informative whitepaper outlines five "checkpoints" for any implementation plan that will help make IP communications a successful proposition.

 
Hosted Email Security: Staying Ahead of New Threats
In the last two years, email has become a fierce battleground between the nefarious forces of spam and malware, and the heroes of messaging protection. The spam volumes increased alarmingly every month, bringing clever new forms of phishing and virus propagation attacks.

 

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 





© 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway