Homework help (unitique constraint) - mysql

enter code hereI have some trouble with homework I got that I need to understand.
Ok so I have 4 tables,
1: costumer
2: order
3: orderedproduct
4. product .
They are linked by foreign key.
I need to make a unique constraint so that a costumer can only place 1 unique order per day. If the same costumer wants to order more on the same day, it has to be written on the already existing order.
TABLES:
costumer
CREATE TABLE COSTUMER (COSTUMERNR INT NOT NULL,
NAME VARCHAR(256),
CITY VARCHAR(256),
PRIMARY KEY (COSTUMERNR)) ENGINE=INNODB;
order
CREATE TABLE ORDER (ORDERNR INT NOT NULL,
ORDERDATE DATETIME,
PRIMARY KEY (ORDERNR)),
FOREIGN KEY (COSTUMERNR) REFERENCES COSTUMER(COSTUMERNR)
ON DELETE CASCADE) ENGINE=INNODB;
orderedproduct
CREATE TABLE ORDEREDPRODUCT (OPNR INT NOT NULL,
AMOUNT INT,
FOREIGN KEY (ORDERNR) REFERENCES ORDER(ORDERNR),
FOREIGN KEY (PRODUCTCODE) REFERENCES PRODUCT (PRODUCTCODE)
ON DELETE CASCADE,
CHECK (AMOUNT=>0)) ENGINE=INNODB;
product
CREATE TABLE PRODUCT (PRODUCTCODE INT NOT NULL,
NAME VARCHAR(256),
TYPE VARCHAR(256),
PRICE FLOAT,
STOCK INT,
PRIMARY KEY (PRODUCTCODE),
CHECK (AMOUNT=>0)) ENGINE=INNODB;

alter table order add unique index(orderdate, COSTUMERNR);

If you're able to split the datetime column into a date column and a time column, you can use a simple constraint:
CREATE TABLE ORDER (
ORDERNR INT NOT NULL,
ORDERDATE DATE,
ORDERTIME TIME,
...
CONSTRAINT [UniqueOrder] UNIQUE NONCLUSTERED
(
COSTUMERNR, ORDERDATE
)

Related

unable to insert primary key in mysql table

I'm a complete beginner in sql and I am using mysql xampp server where I have a customers table and a bookings table . I use mysql data modeler with a ddl to generate the code that creates these tables .
This is how my 2 tables are created below:
BOOKING TABLE:
CREATE TABLE booking (
booking_id INTEGER NOT NULL,
b_city VARCHAR(30),
b_date DATETIME,
departure_date DATETIME,
arrival_date DATETIME,
dep_time DATETIME,
arr_time DATETIME,
seat_type VARCHAR(30),
flight_cost DOUBLE,
total_cost DOUBLE,
booking_state VARCHAR(2),
deposit DOUBLE,
price_remenant DOUBLE,
customer_customer_id VARCHAR(20) NOT NULL,
flight_id INTEGER,
customer_customer_id1 VARCHAR(20) NOT NULL //I don't know why this is created again
);
CREATE UNIQUE INDEX booking__idx ON
booking (
customer_customer_id
ASC );
ALTER TABLE booking ADD CONSTRAINT booking_pk PRIMARY KEY ( booking_id );
ALTER TABLE booking
ADD CONSTRAINT booking_customer_fk FOREIGN KEY ( customer_customer_id )
REFERENCES customer ( customer_id );
ALTER TABLE booking
ADD CONSTRAINT booking_customer_fkv2 FOREIGN KEY ( customer_customer_id1 )
REFERENCES customer ( customer_id );
CUSTOMER TABLE :
CREATE TABLE customer (
customer_id VARCHAR(20) NOT NULL,
first_name VARCHAR(20),
last_name VARCHAR(30),
booking_booking_id INTEGER NOT NULL
);
CREATE UNIQUE INDEX customer__idx ON
customer (
booking_booking_id
ASC );
ALTER TABLE customer ADD CONSTRAINT customer_pk PRIMARY KEY ( customer_id );
ALTER TABLE customer
ADD CONSTRAINT customer_booking_fk FOREIGN KEY ( booking_booking_id )
REFERENCES booking ( booking_id );
Now whenever I try to insert a customer in mysql xampp server with typing
INSERT INTO customer('customer_id')VALUE("1234");
I get the error #1452 - Cannot add or update a child row: a foreign key constraint fails (airline_db.customer, CONSTRAINT customer_booking_fk FOREIGN KEY (booking_booking_id) REFERENCES booking (booking_id)) which I have no idea why since the customer_id is the primary key and the Booking.customer_id the foreign key and I do not know why booking_id is included in this error
This is also how my entities look in data modeler :
I would really appreciate your help .
you can't insert such alues
CREATE TABLE customer (
customer_id VARCHAR(20) NOT NULL,
first_name VARCHAR(20),
last_name VARCHAR(30),
booking_booking_id INTEGER NOT NULL
);
Means that you have at least have to enter 1 booking_id which can't be NULL, but as you don't have a default values for it
Also a foreign key means that you have to have in booking such an id stored before you add a row in customers
Last you have a further problem, as you can only add a booking when you have a customer_id and vice versa , so get rid of the constraint in customer

How to add foreign key to table in mysql

What I am doing incorrect? Trying to create these tables in sqlfiddle
does not work gives
Cannot add foreign key constraint
create table product (
pid int NOT NULL,
name varchar(10),
PRIMARY KEY (pid)
);
create table trans (
tid int NOT NULL ,
productId int NOT NULL,
userId int NOT NULL,
PRIMARY KEY (tid),
FOREIGN KEY (productId) REFERENCES product(pid),
FOREIGN KEY (userId) REFERENCES user1(uid)
);
create table user1 (
uid int NOT NULL ,
location varchar(22),
PRIMARY KEY (uid)
);
As #BillKarwin mentioned, the definitions for tables containing primary keys referenced by the trans table should appear before the definition for the trans table. So you should move the definition for the trans table to last.
However, even doing this still results in an error in SQLFiddle:
SQLFiddle (uncomment the foreign key reference in trans)
SQLFiddle seems to have some sort of problem with accepting this table schema. This is not surprising, as the site seems to have such problems frequently.
What is order you create tables. You need first to create product and user1 and at the end - trans.

composite foreign key add fails

I have got 4 tables here:
CREATE TABLE paper (
id VARCHAR(20) PRIMARY KEY,
name VARCHAR(30)
) ENGINE =INNODB;
CREATE TABLE subscriber (
id VARCHAR(10) PRIMARY KEY,
name VARCHAR(20),
address VARCHAR(30),
suburb VARCHAR(20),
state VARCHAR(3),
postcode VARCHAR(4))
round_id INTEGER NOT NULL,
FOREIGN KEY (round_id) REFERENCES round (id)
ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE = INNODB;
CREATE TABLE current_order (
paper_id VARCHAR(20),
subscriber_id VARCHAR(10),
PRIMARY KEY (paper_id, subscriber_id),
FOREIGN KEY (paper_id) REFERENCES paper (id)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY(subscriber_id) REFERENCES subscriber (id)
ON UPDATE CASCADE ON DELETE RESTRICT)
ENGINE = INNODB;
CREATE TABLE receipt (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
receipt_date DATE,
paid_till_date DATE,
paper_id VARCHAR(20),
subscriber_id VARCHAR(10))
ENGINE = INNODB;
Now table paper has a primary key ID, it is referenced by paper_id in table current_order.
Table subscriber has a primary key ID, it is referenced by subscriber_id in table current_order.
Tabe current_order has a composite primary key (paper_id,subscriber_id).
So these three table has been linked together through the foreign key relationship.
If I want to have the last table receipt linked with these three table, how do I do that? My idea was to
1:set a compound foreign key (paper_id,subscriber_id) referencing to the compound primary key (paper_id,subscriber_id) in table current_order.
2:set two single foreign key (paper_id) and (subscriber_id) referencing to (paper_id) and )subscriber_id) in table current_order separately.
Neither method worked and it came up with error 1452:cannot add or update child row.
So I am really desperate to know what is the proper way to set relationship between table receipt and table current_order?
here is the E-R Digram:
E-R DIGRAM
There is two links between table receipt and table current_order and I am required to set relationship according to that.
i'm not a mysql expert but i would try this:
CREATE TABLE receipt (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
receipt_date DATE,
paid_till_date DATE,
paper_id VARCHAR(20),
subscriber_id VARCHAR(10),
FOREIGN KEY (paper_id,subscriber_id) REFERENCES current_order (paper_id,subscriber_id)
ON UPDATE CASCADE ON DELETE RESTRICT)
ENGINE = INNODB;
does it works?

How to add on delete cascade option in mysql?

I created two tables students and orders and I added a foreign key constraint to the order table but I forgot to add on delete cascade option to this table.
table STUDENTS:
CREATE TABLE STUDENTS (
ID varchar(50) NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
PRIMARY KEY (ID)
)
Table ORDERS
CREATE TABLE Orders
(O_Id int NOT NULL PRIMAY KEY,
Order_No int NOT NULL,ID varchar(50))
Add foreign key to "orders":
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY(ID)
REFERENCES STUDENTS (ID)
I tried this attempt :
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY(ID)
REFERENCES STUDENTS (ID) ON DELETE CASCADE
Thanks.
You have a typo in the Order table. You have PRIMAY where it should be PRIMARY.
After correcting this, I tried creating the tables and all statements worked fine, including the last one.

Nesting of groups or elements

I'm fairly new in Mysql, but I have problem that I cannot solve. I will give you an example to demonstrate it. Please note that I know that (for current example) there are other simpler and more efficient ways to solve it... but just take it as an example of the required procedure.
First the data: The data would be the name of a Person.
CREATE TABLE person(
id INT,
name VARCHAR(100)
) TYPE=innodb;
Second: Group Creation... So this is fairly simple... and could easily done using a table 'group' with a foreignkey to person. These groups could be arbitrary, containing any number of persons, duplicated... or not... (that is simple!!)
Third: MY REAL PROBLEM--- I also would like to have Groups that have other Groups as elements (instead of persons). This is where a really get stuck, because I know how to create a groups of persons, a group of groups (having a self-referencing foreign key)... but I don't know how to create a group that MAY HAVE persons AND Groups.
I appreciate any suggestion to solve this issue.
Thank you very much for your comments.
Regards
ACombo
I'd go with firstly setting up the myGroup and person tables.
Secondly, I'd set up a myGroupGroup table with columns myGroupId, parentMyGroupId. This will allow you to relate group rows to child group rows i.e. "this group has these groups within it". If a group has no rows in this table then it has no child groups within it.
Thirdly, I'd set up a personGroup table with columns personId, myGroupId. This will allow you to relate person rows to a given group. If a group has no rows in this table then it has no persons within it.
CREATE TABLE person(
id INT UNSIGNED PRIMARY KEY,
name VARCHAR(100)
) ENGINE=innodb;
CREATE TABLE myGroup(
id INT UNSIGNED PRIMARY KEY,
groupName VARCHAR(100)
) ENGINE=innodb;
-- Holds groups within groups
CREATE TABLE myGroupGroup(
id INT UNSIGNED PRIMARY KEY,
myGroupId INT UNSIGNED,
parentMyGroupId INT UNSIGNED DEFAULT NULL,
CONSTRAINT `fk_myGroupGroup_group1` FOREIGN KEY (`parentMyGroupId`) REFERENCES `myGroup` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_myGroupGroup_group2` FOREIGN KEY (`myGroupId`) REFERENCES `myGroup` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=innodb;
-- Holds persons within a group
CREATE TABLE personGroup(
id INT,
personId int UNSIGNED NOT NULL,
myGroupId int UNSIGNED NOT NULL,
CONSTRAINT `fk_personGroup_group1` FOREIGN KEY (`myGroupId`) REFERENCES `myGroup` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_personGroup_person1` FOREIGN KEY (`personId`) REFERENCES `person` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=innodb;
I've tweaked your SQL a bit:
1) Replaced TYPE with ENGINE
2) Replaced table name group with myGroup (GROUP is a reserved word)
Good luck!
Alternative:
CREATE TABLE Entity
( EntityId INT --- this id could be AUTO_INCREMENT
, PRIMARY KEY (EntityId)
) ENGINE = InnoDB ;
CREATE TABLE Person
( PersonId INT --- but not this id
, PersonName VARCHAR(100)
, PRIMARY KEY (PersonId)
, FOREIGN KEY (PersonId)
REFERENCES Entity(EntityId)
) ENGINE = InnoDB ;
CREATE TABLE Grouping
( GroupingId INT --- and neither this id
, GroupingName VARCHAR(100)
, PRIMARY KEY (GroupingId)
, FOREIGN KEY (GroupingId)
REFERENCES Entity(EntityId)
) ENGINE = InnoDB ;
CREATE TABLE Belongs
( EntityId INT
, GroupingID INT
, PRIMARY KEY (EntityId, GroupingId)
, FOREIGN KEY (EntityId)
REFERENCES Entity(EntityId)
, FOREIGN KEY (GroupingID)
REFERENCES Grouping(GroupingId)
) ENGINE = InnoDB ;