puk
puk

Reputation: 16762

How to retrieve foreign key and INSERT INTO table (MySQL/InnoDB)

I am doing everything below from the command line and/or mysql> prompt.

I am newbie to DBs and have noticed there are a lot of sites on the structure (tutorials) and definitions (manuals), but none about practical examples. If I have two tables like so

CREATE TABLE IF NOT EXISTS owner
(
  ID INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(32) NOT NULL UNIQUE,
  PRIMARY KEY(ID)
)ENGINE=InnoDB


CREATE TABLE IF NOT EXISTS dog
(
  ID INT NOT NULL AUTO_INCREMENT,
  owner INT NOT NULL,
  name VARCHAR(32) NOT NULL UNIQUE,
  PRIMARY KEY(ID),
  FOREIGN KEY (owner) REFERENCES owner(ID)
)ENGINE=InnoDB

And if I want to add to table dog

INSERT INTO dog (owner, name) VALUES(get_owner_ID("Peter Griffin"), "Brian Griffin");

How do I get the cryptic owner ID from the name ("Peter Griffin")

Upvotes: 0

Views: 3422

Answers (1)

Tom Mac
Tom Mac

Reputation: 9853

You could either run a sub-select when inserting into the dog table or create a user defined function of your own. A user defined function has an advantage over a stored procedure here since it can be called during your insert. Hence:

CREATE TABLE IF NOT EXISTS owner
(
  ID INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(32) NOT NULL UNIQUE,
  PRIMARY KEY(ID)
)ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS dog
(
  ID INT NOT NULL AUTO_INCREMENT,
  owner INT NOT NULL,
  name VARCHAR(32) NOT NULL UNIQUE,
  PRIMARY KEY(ID),
  FOREIGN KEY (owner) REFERENCES owner(ID)
)ENGINE=InnoDB;

Now create the function:

DELIMITER //

DROP FUNCTION IF EXISTS get_owner_id//

CREATE FUNCTION get_owner_id(i_owner_name varchar(32)) returns integer 
READS SQL DATA
BEGIN
 declare v_owner_id int;
 select id into v_owner_id from owner where name = i_owner_name; 
 return v_owner_id;
END//

DELIMITER ;

insert into owner(name) values ('Peter Griffin');
insert into dog (owner,name) values (get_owner_id('Peter Griffin'),'Brian Griffin');

You would have to think of a way of handling the case where the owner does not exist in the owner table of course. Maybe have a default 'unknown owner' in the owner table and return that from the function if no owner is found? Kinda up to you...

Upvotes: 2

Related Questions