mysql - referencing one foreign key to multiple possible primary keys - mysql

I'd like to set up the following database scenario:
CREATE TABLE IF NOT EXISTS `points` (
`po_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`po_north` INT,
`po_east` INT,
PRIMARY KEY (`po_id`),
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `lines`(
`li_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`li_from` INT NOT NULL,
`li_to` INT NOT NULL,
PRIMARY KEY (`li_id`),
FOREIGN KEY (`li_from`) REFERENCES points(`po_id`),
FOREIGN KEY (`li_to`) REFERENCES points(`po_id`),
) ENGINE=InnoDB;
Now I want to set up a third table, that sores some metadata like who created or altered a point or a line:
CREATE TABLE IF NOT EXISTS `metadata` (
`me_type` ENUM('point','line') NOT NULL,
`me_type_id` INT UNSIGNED NOT NULL,
`me_permissions` VARCHAR(255) NOT NULL,
`me_created_by` INT UNSIGNED NOT NULL,
`me_created_on` DATETIME NOT NULL,
`me_last_modified_by` INT UNSIGNED NOT NULL,
`me_last_modified_by` DATETIME NOT NULL,
) ENGINE=InnoDB;
My first approach was to set an ENUM with two types (points and lines). But the problem is still, that I cannot properly reference a foreign key to one of the tables. Is there any recommended solution for such problem in MySQL?
BTW:
The fields for me_created_by and me_last_modified_by shall reference to a table storing some user data.

Your case appears to be yet another instance of the design pattern known as "generalization specialization" or perhaps "table design for class inheritance".
If you think of points and lines as classes of objects, they are both subclasses of some more general class of objects. I'm not sure what name to give the superclass in this case. Here's one of several previous questions that address the same issue.
Extending classes in the database
Fowler gives an extensive treatment of the subject. Your case has an added wrinkle, because you are dealing with metadata. But that need not alter the design. You need a third table, which I'll call "Items" for lack of a better term. The key, "it_id" would be assigned an auto number, and you would add an item every time you add either a point or a line. The two columns "po_id" and "li_id" would not be assigned an auto number. Instead they would be foreign keys, referencing "it_id" in the Items table.
The references to points or lines in the metadata table would then be references to "items" and you could use that information to find information about points or lines as the case may be.
How helpful this is depends on what you are trying to do with the metadata.

Your tables points and lines should contain a foreign key to metadata – not the other way around. Doing so will save you from defining any more complicated table setups. Using this approach, a single metadata-entry could be re-used several times for many different points or lines. This isn't even MySQL specific but a general, normalized database structure.

you can do this using a trigger, you need to trigger an event that can create reference key for either point or line before you insert a record based on respective tables

Related

How to add multivalue atribute to mysql workbench?

How can i add multiple values to my table called 'courier'?
I need to add a second telephone number. The way i created table was:
create table kurier (
id_kurier int not null,
imie varchar(45) not null,
nazwisko varchar(45) not null,
telefon int not null,
id_rejon int,
nr_rej varchar(45) not null,
id_przelozony int,
constraint id_kurier primary key (id_kurier),
constraint id_przelozony foreign key (id_przelozony)
references kurier (id_kurier)
)
There are various options, among them few are as follows:
1- (Discouraged) Add another column to hold telphone2. (but in case you are going to have more numbers then you need more columns)
2- (BEST) Create a child table that stores telephones numbers per courier (as a foregin key). This can hold as many as you need. Move your initial data into child table, drop column from original table.
3- (Alternative) Use a separator to store multiple data as string for eg. using comma (,) the data will look like 99999999, 8888888, 77777777. You can then fetch and split values by the separator you chose for rendering and/or reporting purposes.
Hope this helps !

Is it possible to enforce a constraint in mysql that considers the specific value of a column in another table?

I have a base table that represents hierarchial data using the nested sets model.
CREATE TABLE trees (
id INT NOT NULL AUTO_INCREMENT,
rootId INT DEFAULT NULL,
lft INT NOT NULL,
rgt INT NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY(rootId) REFERENCES trees(id)
);
So this table can contain multiple, separate trees, where rootId points to the top node of each tree.
Now I would like to add a new table to extend trees with a subtype. For example:
CREATE TABLE happyTrees (
treeId INT NOT NULL,
PRIMARY KEY(treeId),
FOREIGN KEY(treeId) REFERENCES trees(id)
);
Rows inserted into happyTrees should point only to root level nodes in trees -- so rows in trees that have a rootId of null.
I can enforce this at the application level, but I am wondering: Is there a more elegant way to enforce this constraint in sql? So that it is only possible to insert a treeId into happyTrees if the corresponding rootId in trees is null?
I would think about the design in a different way.
Either put the attributes in the trees table (a field is_happy) or create a separate tree_attributes table that references the tree structure.
Because ultimately a "happy" tree structure is still a tree structure.
Although I appreciate this does not create a database enforced constraint when inserting rows. And while I prefer database models that prevent bad data from being inserted in the first place, sometimes simplicity is better.
The following works for you specific situation:
CREATE TABLE trees (
id INT NOT NULL AUTO_INCREMENT,
rootId INT DEFAULT NULL,
lft INT NOT NULL,
rgt INT NOT NULL,
PRIMARY KEY(id),
UNIQUE (rootId, id), -- redundant, but needed for foreign key relationship
FOREIGN KEY(rootId) REFERENCES trees(id)
);
CREATE TABLE happyTrees (
treeId INT NOT NULL,
_rootId INT NULL, -- actually, ALWAYS NULL
PRIMARY KEY(treeId),
FOREIGN KEY(_rootId, treeId) REFERENCES trees(rootId, id);
);
This is adding a dummy column which you want to always be NULL. It can then reference the other table, guaranteeing that happy trees only points to the root.
Whether this is more elegant than doing the work in the application (or, better yet in my opinion, a stored procedure), is a matter of aesthetic tastes. It is more clever, though ;)

How do you create a constraint on parent tables that also constrains the child tables?

I am not sure how to phrase the question so I'll illustrate the tables and the explain what I want to achieve.
-- static table of the entity classes supported by the application
create table entity_type (
id integer not null auto_increment,
name varchar(30) not null,
primary key(id)
);
-- static table of statuses supported by the application
create table entity_status (
id integer not null auto_increment,
name varchar(30) not null,
primary key(id)
);
-- table of valid combinations
create table entity_type_entity_status_link (
entity_type_id integer not null,
entity_status_id integer not null,
unique key(entity_type_id, entity_status_id),
foreign key(entity_type_id) references entity_type(id),
foreign key(entity_status_id) references entity_status(id),
);
-- The tables where user types and statuses are defined
create table user_type (
id integer not null auto_increment,
name varchar(30) not null,
entity_type_id integer not null,
primary key(id),
foreign key(entity_type_id) references entity_type(id)
);
create table user_status (
id integer not null auto_increment,
name varchar(30) not null,
entity_status_id integer not null,
primary key(id),
foreign key(entity_status_id) references entity_status(id)
);
-- table of valid pairs
create table user_type_user_status_link (
user_type_id integer not null,
user_status_id integer not null,
unique key(user_type_id, user_status_id),
foreign key(user_type_id) references user_type(id),
foreign key(user_status_id) references user_status(id),
);
The basic premise behind these tables is that the system supports core types and statuses and the user is able to create their own user types and statues that derive from these.
The question I have is that I cannot see a way of creating any database constraints on the user_type_user_status_link table to ensure that the you cannot insert a file_type - file_status pair where the parent entity_type - entity_status is itself not valid. Or is this something that would have to be done with triggers.
The basic premise behind these tables is that the system supports core
types and statuses and the user is able to create their own user types
and statues that derive from these.
Although that sounds like a laudable goal on the surface, the effect is to delegate database design to your users. Database design, because the effect of your desire to set foreign key references to a subset of the rows in entity_type_entity_status_link means each of those subsets is a defacto, unnamed table.
This approach never ends well.
What you've developed is the "One True Lookup Table". Google that for a host of reasons why OTLT is an anti-pattern.
The best solution is to model real things in your tables. (Entity isn't a real thing. It's an abstraction of a real thing.) Something along the lines of either
create table file_status (
file_status varchar(30) primary key
);
or
create table file_status (
file_status_id integer primary key,
file_status varchar(30) not null unique
);
would work well for file statuses.
In the case of the second one, you can set a foreign key reference to either the id number (saves space, requires an additional join) or to the status text (takes more space, eliminates a join). Note that you need the unique constraint on the status text; your original design allows the user to enter the same text multiple times. (You could end up with 30 rows where entity_type.name is 'File'.
You should use triggers for that.
MySQL does not support constraints of the form that will prevent what you want.

PRIMARY KEY definition in MySQL CREATE TABLE statement

What's the difference between this code:
CREATE TABLE samples (
sampleid INT(11) NOT NULL AUTO_INCREMENT,
sampledate DATE NOT NULL,
location VARCHAR(25) NOT NULL,
PRIMARY KEY (sampleid)
)
ENGINE=InnoDB;
and this:
CREATE TABLE samples (
sampleid INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
sampledate DATE NOT NULL,
location VARCHAR(25) NOT NULL,
)
ENGINE=InnoDB;
code?
So a separate PRIMARY KEY statement or as part of a column definition. Same question for UNIQUE INDEX and UNIQUE keyword in column definition.
The second syntax is merely a shortcut allowing you to specify the column and add an index on it in a single clause.
This works out fine in cases where you simply want to create a column and add an index on it.
You'll need to use the first syntax if you want to do something more complicated, such as adding an index based on multiple columns rather than a single column, or if you are adding or changing an index on an existing column; that is, you are not creating the column and the index on it at the same time.
MySQL allows uses the PRIMARY KEY directive to allow you to set the Primary Key dynamically. Supplying PRIMARY KEY as an argument to the constructor can only be called on creating the column. PRIMARY KEY(X), PRIMARY KEY(Y), PRIMARY KEY(Z) allows for changing the primary keys on subsequent queries.
The way I see it is.. The first method is used to create composite keys. While the second method (more readable to me) is primarily used if there is only primary key in the table.
The second method cannot be used if you want to implement composite key
There are many ways to skin a cat and above 2 examples are just 2 of them. They are identical. There's no difference.
They are literally the same. Here is a quick site that shows you the different ways (3) to do it. http://www.java2s.com/Code/SQL/Key/Defineanduseprimarykey.htm

String as primary KEY?

I have this database structure
CREATE TABLE `productinfo` (
`ProductID` int(11) NOT NULL AUTO_INCREMENT,
`ProductName` varchar(255) NOT NULL,
`ProductImage` varchar(255) NOT NULL,
`CategoryID` int(11) NOT NULL,
`SubCategoryID` int(11) NOT NULL,
`ProductBrief` varchar(255) NOT NULL,
`Features` text NOT NULL,
`Specifications` text NOT NULL,
`Reviews` text NOT NULL,
`Price` varchar(255) NOT NULL,
`Status` tinyint(4) NOT NULL,
PRIMARY KEY (`ProductID`)
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=latin1;
I now I need to turn ProductID, CategoryID, and SubCategoryID into a string like Ps-5678 for the part number. ProductID is the primary key so how do i change the structure of the database. CategoryID, and SubCategoryID are primary keys in other tables so how do i handle this..is it as easy as turning
`ProductID` int(11) NOT NULL AUTO_INCREMENT
into a string..and getting rid of
PRIMARY KEY (`ProductID`)
ideas, suggestions anyone
Primary keys are for the database.
Display names are for end users.
Do not confuse one with another! Don't make a primary key out of something that has a meaning. You will regret it sooner or later.
Having a surrogate key / identity / autonumber as a primary key is a very good idea and is used widely in database design.
You can add a column or even a DERIVED COLUMN and add a unique constraint on it.
I believe it should be that easy.
however you need to determine what string type you want to use
http://dev.mysql.com/doc/refman/5.1/en/string-types.html
Your requirement is unclear. How do you get "PS-5678" fro 3 int columns ? There is only 2 components in your example.
Do you just need to CONVERT the 3 INTs to a single CHAR() string ?
If so, the database is fine, no need to change the table at all !?!?! The three components are already available, correctly seperated, as distinct columns. What you are looking for is merely DISPLAYING the three components as a single string.
It's not clear to me from your question just what you do to product, category, and subcategory to make your part number. I'll assume for the sake of argument that you are concatenating them together, like product 123, category 456, subcategory 789 gives part number 123-456-789 or some such.
I like to use natural identifiers as primary keys whenever practical. But "whenever practical" can be a serious constraint. If your natural identifier is derived by somehow combining three other fields, you have four choices:
Make the primary key be the combination of these three fields. This tends to be a pain. All your joins then must match on three fields, searches must test three fields, etc.
Create a new field that is the concatenation of the three fields, and use this as the priamry key. Then whenever one of the "basic" fields changes, also change this concatenated field. This is a very, very bad idea. Don't do it. It's redundant data, with all the bad things that come from redundant data.
Replace the three separate fields with one combined field. This is worse than #2. Now when you need the individual values, you have to take the field apart.
Give up and create a synthetic key, like a serial number. Use this as the primary key, and then just use the natural key for display purposes. If my natural key requires concatenating or otherwise manipulating three fields, I tend to go with this option.