Foreign key created an extra column mySQL - mysql

On of my foreign keys in a table within MySQL added an extra not null column labeled Customers_CustomerID, so I am not able to enter or update the table as required for my assignment. How can I fix this?

Several options. We could 1) drop the column 2) change the column to allow NULL values, 3) change the column definition to specify a non-NULL DEFAULT value for the column, 4) add a BEFORE INSERT trigger to set a non-NULL value to the column, 5) supply a valid value on an INSERT. Lot's of possibilities.
We could provide some additional assistance with the syntax for each of those options, but without the column definition, we can't give the exact syntax that would be required for adding DEFAULT value attribute.
It might not be possible to drop the column, if its used in an index or referenced in a foreign key constraint. The syntax to remove the column would be something like this:
ALTER TABLE mytable DROP customers_customerid ;
The syntax to change the column definition, would be something like this, to specify a DEFAULT value:
ALTER TABLE mytable CHANGE
customers_customerid customers_customerid BIGINT NOT NULL DEFAULT '1' COMMENT 'foo' ;
^^^^^^^^^^^
But we need to know the entire column definition, and repeat that, adding/changing just the bits that need to be changed. The statement above includes guesses about the datatype, et al.
We can get the current definition of the column from the definition of the table with a statement like this:
SHOW CREATE TABLE mytable;
Note: the statement to add a foreign key constraint doesn't add a column to the table. the statement(s) that you executed must have included syntax to add a column.

You haven't really defined what you're trying to fix. What do you mean by saying you are "not able to enter or update the table"? What tool are you trying to update it with?
Here's an example from the MySQL documentation on how you should create two tables and link them with a foreign key:
CREATE TABLE parent (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (
id INT,
parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id)
REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;

Related

Constant column value in MySQL table

I have a table in MySQL. I'd like to set a column value for a table to be a constant integer. How can I do this?
Unfortunately MySQL does not support SQL check constraints. You can
define them in your DDL query for compatibility reasons but they are
just ignored. You can create BEFORE INSERT and BEFORE UPDATE triggers
which either cause an error or set the field to its default value when
the requirements of the data are not met.
So here you can find a way around through MYSQL TRIGGER.
Sample Table:
DROP TABLE IF EXISTS `constantvaluetable`;
CREATE TABLE `constantvaluetable` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`constValue` int(11) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB;
Trigger:
DROP TRIGGER IF EXISTS trigger_const_check;
delimiter //
CREATE TRIGGER trigger_const_check BEFORE INSERT ON constantvaluetable
FOR EACH ROW
BEGIN
IF NEW.constValue <> 71 THEN
SIGNAL SQLSTATE '45000' SET message_text ='Only allowed value is 71';
END IF;
END //
delimiter ;
Test:
INSERT INTO constantvaluetable(constValue) VALUES(71);
INSERT INTO constantvaluetable(constValue) VALUES(66);
Result:
The first insert statement will succeed.
The second insert statement will fail. And the following error message will be shown:
[Err] 1644 - Only allowed value is 71
Note: Assuming your CONSTANT value is 71.
Do you really want to do this?
Would the following not suffice
Select Field1, field2, field3 , 5 as `ConstantField` from myTable
Although 71's trigger solution is the general purpose approach, since it can be used for more complicated conditions, in your case where you just want to check for a constant value, you can stay closer to database logic and add a foreign key to a table that just contains that one allowed value in it, e.g.
create table tbl_checkconst (constraintvalue int primary key);
insert into tbl_checkconst values (71);
alter table yourtable
add constraint fk_yourtable_constcheck
foreign key (column1)
references tbl_chechconst (constraintvalue);
It will actually add some overhead (since it will need to add an index), but would express your constraint in database logic, and your constant usually has a meaning that is in this way designed into the database model (although it is just 1 value now), and you (and any user with the correct permissions) can easily add more allowed values by adding it to the tbl_checkconst-table without modifying your trigger code.
And another reason I added it is that I guess you are really actually looking for a foreign key: In one of your comments you said you are trying to create a "double foreign key to a reference table". If I understand that correctly, you might want to use a composite foreign key, since you are able to combine columns for a foreign key:
alter table yourtable
add constraint fk_yourtable_col1col2
foreign key (column1, column2)
references your_reference_table (refcolumn1, refcolumn2);
You would just set up a CHECK constraint in your table when you set it up. Something like this is all you need in most DBMSs
CREATE someTable
(
someValue int(4) CHECK (someValue = 4)
)
However, with MySQL, CHECK constraints don't behave the same as they do in other DBMSs. The situation is a little more tricky. The answer seems to be here: https://stackoverflow.com/a/14248038/5386243

Check the uniqueness using multiple columns including a substring of a field in a mysql table

I have a database table like this.
CREATE TABLE ItemX(
code varchar(20),
size varchar(12),
type varchar(20),
PRIMARY KEY(code),
CONSTRAINT FOREIGN KEY F1(code) REFERENCES Item(code)
);
code is similar to "xxxx-xxxx-xxxx-0001"
I need to check whether (first 15 characters of code,size,type) is unique before adding a row into the table.
I tried UNIQUE (SUBSTRING(code,1,15),size,type) but it didn't work.
How could I achieve this??
ALTER TABLE `ItemX` ADD UNIQUE `ui`(`code`, `size`, `type`);
I'm not sure if MySQL will allow you pass in a function of a column when creating a unique constraint. If you really want to use only the first 15 characters of the code column, you might want to create a new column for this purpose.

SQL Error 1452: Cannot add or update child row

I'm trying to add a foreign key to an already existing table called OrdersTbl. I added a new column called ApprovedBy like so:
ALTER TABLE OrdersTbl ADD ApprovedBy BIGINT UNSIGNED NOT NULL;
After that, I tried setting it as the foreign key:
ALTER TABLE OrdersTbl
ADD CONSTRAINT ApprovedByEmp FOREIGN KEY (ApprovedBy)
REFERENCES EmployeesTbl(EmployeeID);
But I keep getting
Error 1452: Cannot add or update child row
What am I doing wrong? Should I have set the field ApprovedBy as FOREIGN KEY instead?
When defining
ALTER TABLE OrdersTbl ADD ApprovedBy BIGINT UNSIGNED NOT NULL;
then ApprovedBy cannot be null. The default value will be set which is 0.
Then you apply a foreign key to EmployeesTbl. That means the DB checks that ApprovedBy only contains values that are in EmployeesTbl. But that is not the case. The values are 0.
So either allow null for ApprovedBy and set the values later accordingly or set the correct values before adding the foreign key.
My mistake. It seems that I had to change the values in table OrdersTbl manually. In other words, upon adding the column ApprovedBy, the values set for every entry was of course '0' by default. Since there are no Employees with the ID '0' it failed and sent that error.
After manually changing the values in each entry to '1' (Or any other existing ID in table EmployeesTbl) the problem was fixed.

Add another primary key to table in mysql

I want to add another primary key to a table in mysql.
I use phpmyadmin to communicate with mysql server.
When I click the primary icon for the desired field it gives me this error:
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
Edited:
here's the query:
ALTER TABLE `files` DROP PRIMARY KEY ,ADD PRIMARY KEY ( `file_type` )
How can I do it?
As the name "primary" key says, there may be only one of that (ref: Highlander).
What you might want to try is a UNIQUE KEY, that acts just like a primary for most purpouses. Auto_increment doesn't seem to fulfill any purpouse if used a second time - what'ts the point of two fields carrying exactly the same information?
I believe in your case, what you need is a composite key. I do not know your table structure, but here is a general example taken from here,
CREATE TABLE track(
album CHAR(10),
disk INTEGER,
posn INTEGER,
song VARCHAR(255),
PRIMARY KEY (album, disk, posn)
)
In this case, there is a combination of 3 columns which avoid the duplicate records as you require. Please let me know if I have any mistakes in understanding your scenario.
The error message says it, I think:
the auto_increment column must be key.
So use this query first:
ALTER TABLE 'files' CHANGE 'id' 'id' INT( 10 ) UNSIGNED NOT NULL;
this will remove the auto_increment.
Also, I recommend the Uniqe key as suggested by other answer. I believe there should always (almost) be an Id column in each table.
We can Give Primary Key only once for a table. You can prefer UNIQUE KEY to prevent duplicate records
ALTER TABLE Persons
ADD UNIQUE (P_Id)
You can mark all the fields you want as primary keys, including the existing one. The system internally will drop the existing one and will set all you marked.

How to restrict Blank values in Primary Key column

I have a database of sql server 2008 which I am using to display in a gridview. I have written some code to add new rows in asp.net and C# as Code behind.
When ever a row is added through the Programming I have put some checking which will not allow the required values to be Null.
But, here comes my problem when ever any one of the user adds a new row manually by opening the Database, then a blank value is allowing in the Primary key column which is not 'Null value'.
So, here I have to restrict even not to allow blank values in primary key column, how can I solve this problem.
You need a check constraint
ALTER TABLE [TableName]
ADD CONSTRAINT [CK_PrimaryKeyNotEmpty]
CHECK
(
LEN([ColumnName]) > 0
)
I'm having trouble figuring out what you actual question is.
1) If you need to make a column not accept null values:
Add a constraint to the column in the db:
ALTER TABLE [Table] ALTER COLUMN [Column] INTEGER NOT NULL
See: Altering a column: null to not null
2) If you need to restrict your PK column to only certain values add a constraint:
ALTER TABLE Table
ADD CONSTRAINT CK_Table_Column_Range CHECK (
Column >= 0
)