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”)
You could either run a sub-select when inserting into the
dogtable 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:Now create the function:
You would have to think of a way of handling the case where the owner does not exist in the
ownertable 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…