SQL compound unique key with null - mysql

This is how I create the table:
CREATE TABLE IF NOT EXISTS division (
DIV_ID INTEGER PRIMARY KEY ,
DIV_CODE VARCHAR(10) ,
DIV_NAME VARCHAR(20) ,
GR_ID INTEGER ,
UNIQUE (DIV_CODE, DIV_NAME, GR_ID) ,
CONSTRAINT FK1 FOREIGN KEY (GR_ID) REFERENCES grade(GR_ID) )
If a row exists where DIV_CODE="1", DIV_NAME="1" and GR_ID=1, and I try inserting another row with values "1", "1" and 1, then I get a SQL integrity error, which is expected.
If a row exists where DIV_CODE="1", DIV_NAME="1" and GR_ID=null, and I try inserting another row with vales "1", "1" and null, then the new row is inserted. I now have 2 rows with the same values for each column. Can I setup the table differently to get a similar integrity error for this scenario?
Thanks
EDIT
removed NOT NULL from GR_ID definition.

Related

Key column doesn't exist in table

I'm having trouble adding a foreign key field that references another table.
First I created the users table as so:
CREATE TABLE users (
user_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
userName VARCHAR(256) NOT NULL,
userEmail VARCHAR (256) NOT NULL,
userPwd VARCHAR(256) NOT NULL,
);
then I'd like the quizzes table to have a foreign key that references the user_id from the first table
CREATE TABLE quizzes (
quizId INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
quizName VARCHAR(128) NOT NULL,
quizMax SMALLINT(6) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (user_id)
);
This is throwing the error: 'Key column 'user_id' doesn't exist in table.
Other answers advised to check that DB is InnoDB, which I did, and it is.
Can't understand why it's telling me that user_id doesn't exist, when it clearly does exist in the users table.
Firstly check if table user is created successfully, due to the additional ',' on last column!
Secondly, the column you reffered in FOREIGN KEY(user_id) is not defined in table quizzes, you need to add this column in quizzes table.
First: You do not need the last comma - , in the first CREATE statement. -
Second: you have to create the columns before you can use them in a foreign key constraint and user_id does not exist in the second table at the moment of constraint creation.
Take a look at the example below. The last create succeeds when user_id column is added before the constraint is created:

Insert Into Won't Copy Data "Duplicate entry '0' for key 'PRIMARY'"

All I'm trying to do is use the code below to copy the data from the 'drive' column in the 'vehicle' table to the 'vehicleDrive' column in the 'vehicleDrive' table. But I get an error saying "Duplicate entry for '0' for key 'PRIMARY'".
There is a primary key on both tables with a non-unique id of 0. But it's not letting me change them. How do I fix that?
insert into vehicleDrive (vehicleDrive) (
select distinct(drive) from vehicle);
This beacuse you don't have an auto increment primary key ...(so then insert the second row the primary key is set to 0 for the second time and you get the error)
then try somethings like this in your table
CREATE TABLE `your_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
......
PRIMARY KEY (`id`)
)

Constraint on the same row

If there is possible insert of the same row in table I want to ignore this one. Here the table with foreign key game_id and 2 fields step_num and cell, they could differ and should differ. Cell should be 0-8 and always different for game_id. Step_num the same, but 1-9. But I can't set unique, because the could be the same, but in different game_id's.
Here is part of the script:
create table games(
id int not null auto_increment primary key,
name varchar(255) not null unique ,
status varchar(255) not null,
createDate DATETIME
);
create table steps(
game_id int not null ,
step_num int not null,
cell int not null,
constraint cell_unique on games(id),
constraint chk_number check(step_number > 0 and step_number < 10),
constraint fk_game foreign key (game_id) references games(id) on delete cascade,
constraint chk_cell check(cell >= 0 and cell <= 8)
);
INSERT IGNORE didn't worked adn INSERT ON DUPLICATE KEY I think not what I need. If I try Insert (2, 2, 2) several times, it should ignore. I prevent this actions on the back-end side, but want, that db was correct and automatically prevent from similar actions.
What are the ways to do it correctly?
You have 2 options:
Define composite primary key using ( game_id, step_num, cell ). This restricts repeated row data like 2, 2, 2.
Define a before insert trigger that checks duplicates and
to restrict, updates the same row with same values, affecting no rows.
And as per my knowledge check constraints have no effect in MySQL.

Mysql: insert a new row in a child table with new values except for foreign key column which is obtained from parent table

I'm having this situation. i want to insert a new row into a table which has a foreign key constraint to another table. when i insert a new row, i have new values obtained from user input except for the foreign key column which is to be obtained from the parent table. and the foreign key is an auto_increment primary key in the parent table. here is a the minimized schema to illustrate, only the relevant columns are shown.
CREATE TABLE CUSTOMER (
CUSTOMER_CODE INTEGER NOT NULL AUTO_INCREMENT,
FIRST_NAME VARCHAR (20) NOT NULL,
EMAIL VARCHAR (50) UNIQUE NOT NULL,
.
.
.
PRIMARY KEY (CUSTOMER_CODE)
);
CREATE TABLE BOOKING (
BOOKING_CODE INTEGER NOT NULL AUTO_INCREMENT,
CUSTOMER_CODE INTEGER NOT NULL,
BOOKING_DATE DATE NOT NULL,
.
.
.
PRIMARY KEY (RESERVATION_CODE),
CONSTRAINT BOOKING_CUSTOMER_FK FOREIGN KEY (CUSTOMER_CODE) REFERENCES CUSTOMER
(CUSTOMER_CODE)
);
i want to know the insert statement that will feed into the BOOKING table a new row with values generated based on user interaction with the system for the rest of the columns (like booking_date) but obtain the customer_code from the customer table with a where email= clause with an email obtained from user input.
To combine 2 statements you can use INSERT ... SELECT like this:
INSERT INTO
BOOKING
(CUSTOMER_CODE, BOOKING_DATE)
SELECT
CUSTOMER_CODE, $booking_date
FROM
CUSTOMER
WHERE
CUSTOMER.email=$email
You put your values into SELECT as hard-coded and fetch CUSTOMER_CODE for the appropriate email. But make sure, that you are protected from SQL injection.

insert first data into a recursive sql table

I have the following table:
Create Table if not exists Categories(
category_id int (10) primary key NOT NULL AUTO_INCREMENT,
category_name varchar (20) NOT NULL,
parent_category_id int (10) NOT NULL,
FOREIGN KEY (parent_category_id) REFERENCES Categories(category_id) ON DELETE CASCADE)
The table is holding every category I have on my site - and each category have a parent category (for example 'computer' is the parent category of 'programming')
I have a few top categories which don't have any parent category => parent_category_id =0
My question is how to insert the data for the top categories.
when i'm trying to do:
INSERT INTO `databaseproject`.`categories` (`category_id` ,`category_name` ,`parent_category_id`)
VALUES (NULL , 'computers', '0')
I'm getting the error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`databaseproject`.`categories`, CONSTRAINT `categories_ibfk_1`
FOREIGN KEY (`parent_category_id`) REFERENCES `categories` (`category_id`) ON DELETE CASCADE)
what can I do to insert those categories?
Make parent_category_id nullable, and parent categories have a null parent_category_id, or add a root row with id 0.
You have two problems. First, category_id is an auto_increment field, meaning the database will create a value for you when you insert a new row, so you don't need to provide it. You certainly can't set it to null, since you have specifically said it can't be null, which is absolutely what you want for an auto-incrementing id field. Just change your insert to:
INSERT INTO 'databaseproject'.'categories' ('category_name' ,'parent_category_id')
VALUES ('computers', '0')
But you still have another problem. parent_category_id has to refer to a valid record in the categories table because of the constraint you created. You can solve this problem by allowing the field to be null (get rid of the "NOT NULL" when creating the parent_category_id), and using null instead of zero to indicate this is a top level record.