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

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.

Related

SQL. Create one big table or different tables for earch client "client stock portfolio"? It is training project

What is better for multiply clients?
I create training project and can't understand what's better. Create one big stock portfolio table for all broker's clients or create individual table for each client? Individual table will require add brokerage agreement id for each table's name for it indentification.
DROP TABLE IF EXISTS portfolio;
CREATE TABLE common_portfolio (
common_portfolio_id serial,
brokerage_agreement_id BIGINT UNSIGNED NOT NULL,
type_assets_id BIGINT UNSIGNED NOT NULL,
stock_id BIGINT UNSIGNED NOT NULL,
stock_num BIGINT UNSIGNED NOT NULL,
FOREIGN KEY (brokerage_agreement_id) REFERENCES brokerage_agreement (brokerage_agreement_id),
FOREIGN KEY (type_assets_id) REFERENCES type_assets (type_assets_id),
FOREIGN KEY (stock_id) REFERENCES stock (stock_id)
);
VS
DROP TABLE IF EXISTS portfolio_12345612348; -- number generate from brokerage_agreement_id
CREATE TABLE portfolio_12345612348 (
position_id serial,
type_assets_id BIGINT UNSIGNED NOT NULL,
stock_id BIGINT UNSIGNED NOT NULL,
stock_num BIGINT UNSIGNED NOT NULL,
FOREIGN KEY (type_assets_id) REFERENCES type_assets (type_assets_id),
FOREIGN KEY (stock_id) REFERENCES stock (stock_id)
);
It is always better to keep all them in same table.
Keeping each client's data in a separate table will provide you with best performance only in case when you're looking for this particular customer.
But in all other cases it will be hell: creating/deleting a client will require you to build a dynamical create/drop table statement.
When sometime later you decided to add a column, you'll need to find ALL of those tables somehow and add new column to each one of them.
Even counting number of clients will cause you to write way more code rather than just "select count" statement.
And many more cases
So, use only one table

MySQL for 1-to-1 relation with relational integrity

I'm trying to write a create table statement for the relationship above. I'm not sure if I've represented it correctly but basically every outlet has one manager and every manager manages one outlet. I believe that either one of the primary keys from either table would be able to supply the primary key to the relationship table, can I just pick either of them?
I've also been told that I don't even need to create a separate table for the relationship unless it was a many-to-many relationship?
I'd also like to have some sort of constraint (if thats the right word) where if a store cant be deleted if a manager is attached and also can't delete a manager if they are attached to an outlet.
I've written a create table statement which I think is right but i've been doing this stuff for about 2 weeks and I really have no idea if it is going to behave the way I want:
CREATE TABLE Managers
(
mgr_id int(10) NOT NULL auto_increment,
mgr_name varchar(255),
PRIMARY KEY (mgr_id)
);
CREATE TABLE Outlet
(
store_id int(10) NOT NULL auto_increment,
store_name varchar(255),
PRIMARY KEY (store_id)
);
CREATE TABLE Store_Manager
(
mgr_id int(10) DEFAULT '0' NOT NULL,
store_id int(10) DEFAULT '0' NOT NULL,
PRIMARY KEY (store_id),
FOREIGN KEY (mgr_id) REFERENCES Managers(mgr_id)
ON DELETE NO ACTION
);
Will those statements create tables that behave according to the requirements?
Thanks

Usage of MySQL foreign key referencing multiple columns

I just stumbled across possibility of MySQL foreign key to reference multiple columns. I would like to know what is main purpose of multi-column foreign keys like shown bellow
ALTER TABLE `device`
ADD CONSTRAINT `fk_device_user`
FOREIGN KEY (`user_created_id` , `user_updated_id` , `user_deleted_id`)
REFERENCES `user` (`id` , `id` , `id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
My questions are
Is it the same as creating three independent foreign keys?
Are there any pros / cons of using one or another?
What is the exact use-case for this? (main question)
Is it the same as creating three independent foreign keys?
No. Consider the following.
First off, it is not useful to think of it as (id,id,id), but rather (id1,id2,id3) in reality. Because a tuple of (id,id,id) would have no value over just a single column index on id. As such you will see the schema below that depicts that.
create schema FKtest001;
use FKtest001;
create table user
( id int auto_increment primary key,
fullname varchar(100) not null,
id1 int not null,
id2 int not null,
id3 int not null,
index `idkUserTuple` (id1,id2,id3)
);
create table device
( id int auto_increment primary key,
something varchar(100) not null,
user_created_id int not null,
user_updated_id int not null,
user_deleted_id int not null,
foreign key `fk_device_user` (`user_created_id` , `user_updated_id` , `user_deleted_id`)
REFERENCES `user` (`id1` , `id2` , `id3`)
);
show create table device;
CREATE TABLE `device` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`something` varchar(100) NOT NULL,
`user_created_id` int(11) NOT NULL,
`user_updated_id` int(11) NOT NULL,
`user_deleted_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_device_user` (`user_created_id`,`user_updated_id`,`user_deleted_id`),
CONSTRAINT `device_ibfk_1` FOREIGN KEY (`user_created_id`, `user_updated_id`, `user_deleted_id`) REFERENCES `user` (`id1`, `id2`, `id3`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
show indexes from device; -- shows 2 indexes (a PK, and composite BTREE)
-- FOCUS heavily on the `Seq_in_index` column for the above
-- xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
drop table device;
drop table user;
create table user
( id int auto_increment primary key,
fullname varchar(100) not null,
id1 int not null,
id2 int not null,
id3 int not null,
index `idkUser1` (id1),
index `idkUser2` (id2),
index `idkUser3` (id3)
);
create table device
( id int auto_increment primary key,
something varchar(100) not null,
user_created_id int not null,
user_updated_id int not null,
user_deleted_id int not null,
foreign key `fk_device_user1` (`user_created_id`)
REFERENCES `user` (`id1`),
foreign key `fk_device_user2` (`user_updated_id`)
REFERENCES `user` (`id2`),
foreign key `fk_device_user3` (`user_deleted_id`)
REFERENCES `user` (`id3`)
);
show create table device;
CREATE TABLE `device` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`something` varchar(100) NOT NULL,
`user_created_id` int(11) NOT NULL,
`user_updated_id` int(11) NOT NULL,
`user_deleted_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_device_user1` (`user_created_id`),
KEY `fk_device_user2` (`user_updated_id`),
KEY `fk_device_user3` (`user_deleted_id`),
CONSTRAINT `device_ibfk_1` FOREIGN KEY (`user_created_id`) REFERENCES `user` (`id1`),
CONSTRAINT `device_ibfk_2` FOREIGN KEY (`user_updated_id`) REFERENCES `user` (`id2`),
CONSTRAINT `device_ibfk_3` FOREIGN KEY (`user_deleted_id`) REFERENCES `user` (`id3`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
show indexes from device; -- shows 4 indexes (a PK, and 3 indiv FK indexes)
-- FOCUS heavily on the `Seq_in_index` column for the above
There are 2 sections there. The show indexes from device will show the difference of, in the top part, 2 indexes maintained. In the bottom part, 4 indexes maintained. If for some reason the index tuple in the top part is useful for the system, then that tuple approach is certainly the way to go.
The reason is the following. The tuple exists as a group. Think of it as an instance of a set that has meaning as a group. Compare that to the mere existence of the individual parts, and there is a difference. It is not that the users exist, it is that there is a user row that has that tuple as an existence.
Are there any pros / cons of using one or another?
The pros were described above in the last paragraph: existence as an actual grouping in the user table as a tuple.
They are apple and oranges and used for different purposes.
What is the exact use-case for this? (main question)
A use case would be something that requires the existence of the tuple as a group, as opposed to the existence of the individual items. It is used for what is called compositing. Compositing FK's in particular. See this answer of mine Here as one case.
In short, it is when you want to enforce special hard to think of solutions that require Referential Integrity (RI) at a composited level (groupings) of other entities. Many people think it can't be done so they first think TRIGGER enforcement or front-end Enforcement. Fortunately those use cases can be achieved via the FK Composites thus leaving RI at the db level where it should be (and never at the front-end).
Addendum
Request from OP for a better real life example than the link above.
Consider the following schema:
CREATE SCHEMA testRealLifeTuple;
USE testRealLifeTuple;
CREATE TABLE contacts
( id INT AUTO_INCREMENT PRIMARY KEY,
fullname VARCHAR(100) NOT NULL
-- etc
);
CREATE TABLE tupleHolder
( -- a tuple representing a necessary Three-some validation
-- and vetting to get financing
--
-- If you can't vett these 3, you can't have my supercomputer financed
--
id INT AUTO_INCREMENT PRIMARY KEY,
CEO INT NOT NULL, -- Chief Executive Officer
CFO INT NOT NULL, -- Chief Financial Officer
CIO INT NOT NULL, -- Chief Geek
creditWorthiness INT NOT NULL, -- 1 to 100. 100 is best
-- the unique index is necessary for the device FK to succeed
UNIQUE INDEX `idk_ContactTuple` (CEO,CFO,CIO), -- No duplicates ever. Good for re-use
FOREIGN KEY `fk_th_ceo` (`CEO`) REFERENCES `contacts` (`id`),
FOREIGN KEY `fk_th_cfo` (`CFO`) REFERENCES `contacts` (`id`),
FOREIGN KEY `fk_th_cio` (`CIO`) REFERENCES `contacts` (`id`)
);
CREATE TABLE device
( -- An Expensive Device, typically our Supercomputer that requires Financing.
-- This device is so wildly expense we want to limit data changes
--
-- Note that the GRANTS (privileges) on this table are restricted.
--
id INT AUTO_INCREMENT PRIMARY KEY,
something VARCHAR(100) NOT NULL,
CEO INT NOT NULL, -- Chief Executive Officer
CFO INT NOT NULL, -- Chief Financial Officer
CIO INT NOT NULL, -- Chief Geek
FOREIGN KEY `fk_device_2_tuple` (`CEO` , `CFO` , `CIO`)
REFERENCES `tupleHolder` (`CEO` , `CFO` , `CIO`)
--
-- Note that the GRANTS (privileges) on this table are restricted.
--
);
DROP SCHEMA testRealLifeTuple;
The highlights of this schema come down to the UNIQUE KEY in tupleHolder table, the FK in device, the GRANT restriction (grants not shown), and the fact that the device is shielded from tomfoolery edits in the tupleHolder because of, as mentioned:
GRANTS
That the FK must be honored, so the tupleHolder can't be messed with
If the tupleHolder was messed with (the 3 contacts ids), then the FK would be violated.
Said another way, it is NO WAY the same as the device having an FK based on a single column in device, call it [device.badIdea INT], that would FK back to tupleHolder.id.
Also, as mentioned earlier, this differs from merely having the contacts exist. Rather, it matters that the composition of contacts exists, it is a tuple. And in our case the tuple has been vetted, and has a credit worthiness rating, and the id's in that tuple can't be messed with, after a device is bought, unless sufficient GRANTS allow it. And even then, the FK is in place.
It may take 15 minutes for that to sink in, but there is a Huge difference.
I hope this helps.

How to create tables to store different fields and reference them?

I have a set of users of different types, each type has individual set of fields storing user settings. My thought was to store user_id and user_type in one table with common set of fields and to move other settings to a separate tables. But the problem is how to link user from common table with his details in separate table. I see one solution is to store table name associated with certain user type in another table. But is it the best solution?
CREATE TABLE IF NOT EXISTS `mydb`.`user` (
`user_id` INT NOT NULL,
`user_name` INT NOT NULL,
`user_type` INT NULL,
PRIMARY KEY (`user_id`, `user_name`),
UNIQUE INDEX `adv_id_UNIQUE` (`user_id` ASC),
INDEX `adv_type_idx` (`user_type` ASC),
CONSTRAINT `adv_type`
FOREIGN KEY (`user_type`)
REFERENCES `mydb`.`user_type` (`type_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
CREATE TABLE IF NOT EXISTS `mydb`.`user_type` (
`type_id` INT NOT NULL,
`type_table` VARCHAR(45) NULL,
UNIQUE INDEX `type_id_UNIQUE` (`type_id` ASC),
PRIMARY KEY (`type_id`))
//TABLES WITH SEPARATE SET OF FIELDS
CREATE TABLE IF NOT EXISTS `mydb`.`user_details_admin` (
`user_id` INT NOT NULL,
`user_admin` VARCHAR(45) NULL,
PRIMARY KEY (`user_id`))
CREATE TABLE IF NOT EXISTS `mydb`.`user_details_moderator` (
`user_id` INT NOT NULL,
`user_moderator` VARCHAR(45) NULL,
PRIMARY KEY (`user_id`))
This appears to be a situation where you want to model inheritance in your database.
Rather than storing the user_details_ table names in the user_types table, something akin to the following may serve you better:
CREATE TABLE IF NOT EXISTS 'mydb'.'user' (
'user_id' INT NOT NULL,
'type_id' INT NOT NULL,
'commonfield1' datatype (NOT) NULL,
'commonfield2' datatype (NOT) NULL,
'commonfield...' datatype (NOT) NULL,
PRIMARY KEY ('user_id', (other field as needed)),
UNIQUE INDEX 'adv_id_UNIQUE' ('user_id' ASC),
INDEX 'adv_type_idx' ('type_id' ASC),
CONSTRAINT 'adv_type'
FOREIGN KEY ('type_id')
REFERENCES 'mydb'.'user_type' ('type_id')
ON DELETE NO ACTION
ON UPDATE NO ACTION)
CREATE TABLE IF NOT EXISTS 'mydb'.'user_type' (
'type_id' INT NOT NULL,
'type_name' VARCHAR(45) NOT NULL,
UNIQUE INDEX 'type_id_UNIQUE' ('type_id' ASC),
UNIQUE INDEX 'type_name_UNIQUE' ('type_name' ASC),
PRIMARY KEY ('type_id'))
//TABLES WITH SEPARATE SET OF FIELDS
CREATE TABLE IF NOT EXISTS 'mydb'.'user_details_admin' (
'user_id' INT NOT NULL,
'type_id' INT NOT NULL,
'adminfield1' datatype (NOT) NULL,
'adminfield...' datatype (NOT) NULL,
PRIMARY KEY ('user_id'))
CONSTRAINT user_type_FK
FOREIGN KEY ('user_id', 'type_id')
REFERENCES 'mydb'.'user' ('user_id', 'type_id')
ON DELETE NO ACTION
ON UPDATE NO ACTION)
CREATE TABLE IF NOT EXISTS 'mydb'.'user_details_moderator' (
'user_id' INT NOT NULL,
'type_id' INT NOT NULL,
'moderatorfield1' datatype (NOT) NULL,
'moderatorfield...' datatype (NOT) NULL,
PRIMARY KEY ('user_id'))
CONSTRAINT user_type_FK
FOREIGN KEY ('user_id', 'type_id')
REFERENCES 'mydb'.'user' ('user_id', 'type_id')
ON DELETE NO ACTION
ON UPDATE NO ACTION)
This design assumes that a user may be of one and only one type. You'll need to insure that, for example, a moderator is only added to the user_details_moderator table using triggers or views, and/or by handling it in your application code. MySQL doesn't implement check constraints on tables. You'll likely want to create views, anyway, in order to avoid having to write the JOIN between the user table and the sub-type tables every time you want to query a specific sub-type.
Note: The INDEX on type_id in the user table may not be useful or necessary.
This is not the only way to model your data. If you have few fields that are distinct between types and/or are willing to have fields you know will be NULL in your table, you can just add all the fields to the user table. Other than the a priori NULL fields issue, a major difference between these approaches comes with the addition of a new user_type with new distinct fields. In the example I provided, you would need to add a new table. In the single-table design, you would need to add new nullable fields to the user table. Which is easier to maintain is really up to you, but I personally prefer the table-per-type design because in my uses adding a table is relatively trivial and I dislike intentionally adding fields that I know will contain NULL 'values' without serious optimization advantages (that don't exist in my case, but might in yours).
See also How do you effectively model inheritance in a database?, and/or search for "inheritance" under the database tag for further information.
I think creating a user_type_parameters with columns user_id, parameter_key, parameter_value could be an interesting solution as it would give you more flexibility.
the parameter_key column would be the name of some parameter like one of the columns on the user_details_admin table, and on the parameter_value column you would inster its correspondent value.
Of course on the application side you would have to know what keys to expect for each user type.
please fell free to ask if you have any doubts about my explanation.

DBMS design for multivalued attributes

I have to design a database where some information about usage of printer resource is to be recorded in a mysql database. What is the best way to design the database?
I do not want to create a table for each student as there would be around 6000 tables and which would keep growing each year if archives are to be maintained. Also it is difficult to create tables based on registration number of student. Is there a better way than storing multivalued attribute for details of printing. Please suggest some solutions. Also querying should be effective.
There is no need to create different tables for each student.
Just create a Table STUDENT which will contain the personal details of the student identified by their Registration number (lets say Regno-PrimaryKey).
And then another Table RESOURCE, which will have the following schema:
-RecNo Integer PK
-StudentID Foriegn key referenced to Regno in the Student Table
-Usage
or Data,Time(if you require)
This will work for and you need not have to create 6000 or more tables.
You have given very few information, but here is a shot:
create table student
(
registration_no varchar(50) not null primary key,
first_name varchar(50),
last_name varchar(50),
registration_year integer not null
);
create table printer
(
printer_id integer not null primary key,
printer_name varchar(50) not null,
ip_address varchar(50) not null,
queue_name varchar(50) not null
);
create unique index idx_printer_name on printer (printer_name);
create table printer_usage
(
usage_id integer not null primary key,
student_reg_no integer not null,
printer_id integer not null,
usage_date datetime not null,
pages integer not null
);
alter table printer_usage
add constraint fk_usage_student
foreign key (student_reg_no) references student (registration_no);
alter table printer_usage
add constraint fk_usage_printer
foreign key (printer_id) references printer (printer_id);
You will probably need to add more columns to the tables to store all the things you need. I was just guess stuff that you might want to store.