Here is my SQL:
INSERT INTO film (film_id, title, description, release_year, language_id, original_language_id,
rental_duration, rental_rate, length, replacement_cost, rating, special_features, last_update)
VALUES ('1001','1 st Grade FBI Agent','An undercover FBI agent must pretend to be
a 1st grade teacher to catch the bad guy', '2014','2','null', '5', '4.99', '123', '2014',
'20.99', 'PG-13', 'Tailers');
Here is the error I get when I run it. This is a preset database I'm using for an assignment for a class, and I was told to insert a new row into the film table.
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (sakila.film, CONSTRAINT fk_film_language_original FOREIGN KEY (original_language_id) REFERENCES language (language_id) ON UPDATE CASCADE)
The value for original_language_id must match the value of language_id for one row in the language table. This requirement is due to a foreign key on the film table.
If this value is an integer it should not be surrounded by quotes.
Your SQL Statement is trying to INSERT 'null' value for the original_language_id field in the film table.
It looks like this original_language_id is a FOREIGN KEY that references the language_id in the language table and is likely the PRIMARY KEY on that table.
Looks like you are giving 'null' as value for original_language_id. Check, whether you have null as value in your language table. If you want to insert value null .... write it just null not 'null'.
It seems that "original_language_id" is a foreign key from the "language" table and the value which you are trying to insert i.e 'null' in this case is not in the parent table(language).
I'm seeing a few problems in your statement. But to answer the question that was asked, look at the "language" table. The value you put in original_language_id must be one of the values in the language.language_id column (or null, see below).
As for the other stuff, several users have already commented on the null value. null is a keyword and should not be in quotes.
ALso, your last 4 values seem to be in a different order than the field list.
Related
CREATE TABLE IF NOT EXISTS students (
student_id INT,
name VARCHAR(24),
major VARCHAR(24),
PRIMARY KEY(student_id)
);
SELECT * FROM student;
INSERT INTO students VALUES(1,'Jack','Biology');
You're specifying the primary key (student_id) and from the error it already exists. You have a few options:
Don't specify the primary key. It should be set to autoincrement anyway, assuming that this is the primary table that students are entered into, and from the name of the table (students) it seems like it is. Then the query will be:
INSERT INTO students VALUES('Jack','Biology');
and then the table will autoincrement the primary key to the next pointer.
Use INSERT IGNORE. This will silently fail if you try to insert a student ID that already exists (or on any query that violates unique keys).
INSERT IGNORE INTO students VALUES(1, 'Jack','Biology');
This will not cause table changes, but it will also not cause an error that interrupts the script, and it will insert any rows that don't fail, say if you had multiple values inserted. The plain INSERT will fail for the entire list, not just the erroneous value.
Use ON DUPLICATE KEY UPDATE. This will update a list of values if it encounters a duplicate key.
INSERT INTO students VALUES(1, 'Jack','Biology')
ON DUPLICATE KEY UPDATE name = values(name), major = values(major);
In this case, you will change the values in the table that match the key. In this case, whichever student is student_id 1 will have its name and major updated to the supplied values. For instance, let's say that Jack changed his major to Chemistry. This would update student_id 1 to Jack, Chemistry and reflect his new major.
Use REPLACE INTO. I avoid this one. It is similar to ON DUPLICATE KEY UPDATE, but it removes the old entry and replaces it with a new one with a new ID. This can cause you problems with foreign keys, and also if you have a small primary key and you constantly replace into it, you can end up with a primary id that's bigger than the limits you set.
Well, your student_id is primary key, clearly that table is already exist with some data with student_id=1 hence you cannot insert another row with the same primary key value.
SQL query:
INSERT INTO `website_categorization`.`category_keyword` (
`ID` ,
`ID_Category` ,
`Keyword` ,
`Score`)
VALUES (
NULL , '18', 'free mail', ''
), (
NULL , '18', 'web email free', ''
)
MySQL said:
#1062 - Duplicate entry '18-free mail' for key 'ID_Category'
It shows this duplicate entry error even though there is no entry at row no 1062. ( ID is primary key, and unique(ID_Category,Keyword) ).
Can u help me in this?...
You already have a row in your database with the values '18' and 'free mail'. You can't have two such rows because of the unique constraint. You have some choices:
Remove the original row and try your insert again: DELETE FROM yourtable WHERE ID_Category = '18' AND Keyword = 'free mail'.
Remove the unique constraint to allow both rows to exist.
Use INSERT IGNORE to ignore the error.
Use REPLACE instead of INSERT to replace the old row with the new row.
Attempt the INSERT knowing that the client-side will be alerted of the error.
Well, it means that the data you are inserting breaks the unique constraints. From the error messasge I'd say some data already exists with the pair (18, 'free mail') - you say that is constrained to be unique.
The row number is not an indication, because it doesn't correspond to the key.
Your ID_category key is declared as unique and thus you cannot have two entries with the same value.
If your ID field is truly a primary key, it is mostly likely (or should be) auto-incremented. So leave that field out of the INSERT query.
That is MySQL Error number 1062, not row number. The error means duplicate entry. You are inserting NULL and '18' twice in ID and ID_Category respectively, so it will throw this error the 2nd time you do it. ID_Category is very likely the name of your index. You can do a
show index from website_categorization.category_keyword
to see the index name.
I have this mysql query (which add values from a form into a table upon submission). It returns an error message:
$query = "INSERT INTO customers(customerNumber, customerName, contactLastName, contactFirstName, phone, addressLine1, addressLine2, city, state, postalCode, country, salesRepEmployeeNumber, creditLimit) VALUES ('$customer_number', '$customer_name', '$last_name', '$first_name', '$phone_number', '$address_1', '$address_2', '$city', '$state', '$postal_code', '$country', '$sales_number', '$credit_limit')";
$result = mysqli_query($dbc, $query)
or die(mysqli_error($dbc));
ERROR MESSAGE:
Cannot add or update a child row: a foreign key constraint fails (ikb2014_employees.customers, CONSTRAINT customers_ibfk_1 FOREIGN KEY (salesRepEmployeeNumber) REFERENCES employees (employeeNumber))
I am having a hard time deciphering where the 'foreign key constraint' fails. How can I change the the options in the database for the specific table to that I am able so run the query?
This is what the options in the phpMyAdmin show for the table employees and the column employeeNumber (assuming that is where the error is being caused).
# Name Type Collation Attributes Null Default Extra Action
1 employeeNumber int(11) No None AUTO_INCREMENT
I have not worked with a database before so it is hard for me to understand where and why the issue occurs. Any input on how to fix the constraint to properly run the query would be appreciated.
A failure of a foreign key constaint means that you are trying to enter data into a column of one table that does not exist in another table. The foreign key constraint is put in place to ensure that the data you insert into the child table exists in the parent table.
In your case, you're attempting to insert (or not attempting to insert) data in to the salesRepEmployeeNumber column of the customers table. In order to successfully do so, you need to ensure that the value that is provided for salesRepEmployeeNumber exists in the employeeNumber column of the employees table.
The foreign key constraint error is objecting to the value being assigned to the salesRepEmployeeNumber column. The foreign key constraint is checking that the value supplied for that column matches a row in employees table, it;s looking for a row that has the same value for employeeNumber, and it's not finding one.
If you don't want the database to enforce a foreign key constraint, then don't define one.
If you do want the constraint, then that's saying that you have to supply either a valid employeeNumber or a NULL value for salesRepEmployeeNumber.
From the code we're seeing, it looks like the SQL statement is vulnerable to SQL Injection. (We're not seeing any guarantees about the values of the variables being incorporated into the SQL text. If any of those values is potentially unsafe, then those values need to be properly escaped, for example, using mysqli_real_escape_string function.
A better pattern is to use a prepared statement with bind placeholders.
If your foreign key is wrong, you can easily remove it in phpMyAdmin.
Go to the customers table, click on 'structure' tab and at the bottom there will be an +Indexes hidden list, expand it and click DROP on the selected index.
I´m creating a database addrees and I want to know what I need to set in Mysql to don´t store repeat values?
Like
Addrees 1 ("teste",1,new york,eua);
Addrees 2 ("teste",1,new york,eua);
If this happen my database will not store.
So what I need to do?
To alter an already existing table, run this MySQL command:
alter table yourtablename add unique index(firstcolumn, secondcolumn, thirdcolumn, fourthcolumn);
That'll add the unique constraint to the specified columns. Here's how to specify such a constraint in the CREATE TABLE.
CREATE TABLE buyers (
buyer_id INT UNSIGNED NOT NULL,
first_name CHAR(19) NOT NULL,
last_name CHAR(19) NOT NULL,
age SMALLINT NOT NULL,
post_code SMALLINT NOT NULL,
UNIQUE idx_flname_age (first_name,last_name,age)
);
The primary key constraint will do this too, as mentioned by #Ajeesh
EDIT:
As per the suggestion in the comment, if you want to avoid errors generated by this unique constraint, you have three good options:
INSERT IGNORE
and
INSERT...ON DUPLICATE KEY UPDATE
and
REPLACE
INSERT IGNORE will not do anything if the insert violates the unique constraint, except log a harmless warning. The table will be left as is, and no error would be reported. This may be desireable in some cases.
More commonly is the second option, ON DUPLICATE KEY UPDATE, which says "Well, if the key already exists, then update that key's row like this instead."
And lastly is REPLACE, which will, if the key already exists, delete the row, then do an INSERT as normal. If the key did not exist previously, it will simply act as an INSERT.
This stack overflow answer has some examples.
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
You need to call these fields a UNIQUE_KEY
To make a column to be distinct you need to have Primary Key constraint/Unique Key. Primary key is used for relating one table with another and it's values should not be NULL. But in your case you can have Unique constraint to store only unique/distinct values.
I've been reading up on how to use MySQL insert on duplicate key to see if it will allow me to avoid Selecting a row, checking if it exists, and then either inserting or updating. As I've read the documentation however, there is one area that confuses me. This is what the documentation says:
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed
The thing is, I don't want to know if this will work for my problem, because the 'condition' I have for not inserting a new one is the existence of a row that has two columns equal to a certain value, not necessarily that the primary key is the same. Right now the syntax I'm imagining is this, but I don't know if it will always insert instead of replace:
INSERT INTO attendance (event_id, user_id, status) VALUES(some_event_number, some_user_id, some_status) ON DUPLICATE KEY UPDATE status=1
The thing is, event_id and user_id aren't primary keys, but if a row in the table 'attendance' already has those columns with those values, I just want to update it. Otherwise I would like to insert it. Is this even possible with ON DUPLICATE? If not, what other method might I use?
The quote includes "a duplicate value in a UNIQUE index". So, your values do not need to be the primary key:
create unique index attendance_eventid_userid on attendance(event_id, user_id);
Presumably, you want to update the existing record because you don't want duplicates. If you want duplicates sometimes, but not for this particular insert, then you will need another method.
If I were you, I would make a primary key out of event_id and user_id. That will make this extremely easy with ON DUPLICATE.
SQLFiddle
create table attendance (
event_id int,
user_id int,
status varchar(100),
primary key(event_id, user_id)
);
Then with ease:
insert into attendance (event_id, user_id, status) values(some_event_number, some_user_id, some_status)
on duplicate key
update status = values(status);
Maybe you can try to write a trigger that checks if the pair (event_id, user_id) exists in the table before inserting, and if it exists just update it.
To the broader question of "Will INSERT ... ON DUPLICATE respect a UK even if the PK changes", the answer is yes: SQLFiddle
In this SQLFiddle I insert a new record, with a new PK id, but its values would violate the UK. It performs the ON DUPLICATE and the original PK id is preserved, but the non-UK ON DUPLICATE KEY UPDATE value changes.