Am trying to create the following table:
create table Cust (Name varchar(50) UNIQUE, Cat1 varchar(50), RowID int NOT NULL AUTO_INCREMENT, PRIMARY KEY (Name));
the error I get is
Incorrect table definition; there can be only one auto column and it
must be defined as a key
I want to index by the "Name", not the RowID. So even if I end it with:
...PRIMARY KEY (Name, RowID));
It fails. Of course ...PRIMARY KEY (RowID, Name)); works but is not what I want.
Can someone help me see the light please?
Thanks
You just need to make a KEY (aka index) for the auto-inc column. It doesn't have to be the primary key, but it must be the left-most column in some index.
create table Cust (
Name varchar(50),
Cat1 varchar(50),
RowID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (Name),
KEY (RowId)
);
Don't add the UNIQUE option to the name column. That creates an extra superfluous unique index, which you don't need. Any PRIMARY KEY is already unique.
I'll comment that auto-inc is not the same thing as rowid. Don't expect auto-inc to have consecutive values.
Related
Table 1
create table personal(
id int not null auto_increment unique,
name char(20) not null,
age int not null,
city varchar(20) not null default 'Delhi'
);
insert into personal(name,age,city) values
('anubhav',22,'delhi'),
('rohit',24,'agra');
Table 2
create table applications(
app_id int(5) not null auto_increment unique,
city varchar(10) not null default 'Delhi'
);
insert into applications(city) values
('kolkata'),
('mumbai'),
('mumbai'),
('delhi'),
('agra'),
('agra');
Then i apply foreign key here with the help of Alter command-
alter table personal add foreign key(city) references applications(app_id)
but i am getting an error: ERROR 1005 (HY000): Can't create table 'student.#sql-f40_3' (errno: 150)
MySQL specifies:
Conditions and Restrictions
1.Corresponding columns in the foreign key
and the referenced key must have similar data types. The size and sign
of fixed precision types such as INTEGER and DECIMAL must be the same.
The length of string types need not be the same. For nonbinary
(character) string columns, the character set and collation must be
the same.
2.MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist. This index might be silently dropped later if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
The data type must be the same.
You could do:
alter table personal add foreign key(city) references applications(city)
But, the columns on both tables should be indexed.
See here
you desing in not normalized
your personal table should only reference the id.
City name in the applications should be unique, so i added it in the create table, there is no need for two or more delhis in a table(see normalisation)
If you really want to use in personal the city name, you must like i already made refernece the coty name of appcations or define a KEY for that column.
Further the datatyoes of the columns must always be the saem in both table for the foreign key
create table personal(
id int not null auto_increment unique,
name char(20) not null,
age int not null,
city int not null default 0
);
create table applications(
app_id int not null auto_increment primary key,
city varchar(10) not null unique default 'Delhi'
);
alter table personal add foreign key(city) references applications(app_id)
You have small bugs such as not putting null in the insert for the autoincrement and if it is primary key you should not put not null.
Table personal
create table personal(
id int auto_increment primary key,
name char(20) not null,
age int not null,
city varchar(20) not null default 'Delhi'
);
insert into personal values (null,'anubhav',22,'delhi'),
(null,'rohit',24,'agra');
Table applications
create table applications(
app_id int(5) auto_increment primary key,
city varchar(10) not null default 'Delhi'
);
insert into applications values(null,'kolkata'),
(null,'mumbai'),
(null,'mumbai'),
(null,'delhi'),
(null,'agra'),
(null,'agra');
Alter table
alter table personal add foreign key(city) references applications(app_id)
I was about to create two tables (1st table: fooditem_tbl & 2nd table: orderitem_tbl). I was planning to create 2 foreign keys (ITEM_NAME,UNIT_PRICE) on the 2nd table. I wasn't able to run the query of the 2nd table(orderitem_tbl), due to an error which is near at "INDEX". I kept looking at my query, and I still don't know what's the cause of the error.
My first table , this one works
CREATE TABLE FOODITEM_TBL
(ITEM_ID INT AUTO_INCREMENT,
ITEM_NAME VARCHAR(50) UNIQUE,
UNIT_PRICE DOUBLE UNSIGNED,
ITEM_QUANTITY INT UNSIGNED,
IN_STOCK BOOLEAN,
PRIMARY KEY (ITEM_ID, ITEM_NAME, UNIT_PRICE));
The 2nd table, which is below fails to create
CREATE TABLE ORDERITEM_TBL(
ORDER_ID INT AUTO_INCREMENT,
ITEM_NAME VARCHAR(50) UNIQUE,
UNIT_PRICE DOUBLE UNSIGNED,
ITEM_QUANTITY INT UNSIGNED,
CUSTOMER_NAME VARCHAR(50),
ADDRESS VARCHAR(50),
CONTACT_NUMBER VARCHAR(50),
PRIMARY KEY (ORDER_ID),
INDEX (ITEM_NAME,UNIT_PRICE),
FOREIGN KEY (ITEM_NAME,UNIT_PRICE) REFERENCES
FOODITEM_TBL(ITEM_NAME,UNIT_PRICE)
) ENGINE = InnoDB;
P.S Please help
Q: What is causing the error? How can I fix it?
For InnoDB, there must be an index on the target table, on the target column(s). Datatypes of the referencing foreign key column(s) must match the datatypes of the target column(s).
Before creating the foreign key constraint, make sure a suitable index exists on the target table, e.g.
CREATE UNIQUE INDEX `FOODITEM_TBL_UX3` ON `FOODITEM_TBL` (`ITEM_NAME`, `UNIT_PRICE`) ;
Given that ITEM_NAME is unique in the target table, we know that the combination of ITEM_NAME and UNIT_PRICE will also be unique. I'm not sure why we wouldn't just define a foreign key constraint on just ITEM_NAME, but that doesn't really address the question that was asked.
Personally, I would avoid floating point datatypes (e.g. DOUBLE) for columns involved in foreign key constraints.
I previously created a table using the following SQL code:
CREATE TABLE myTable (
id_A BIGINT NOT NULL,
id_B INT NOT NULL,
some_info varchar(255),
some_info2 varchar(255),
PRIMARY KEY (id_A)
)
In the previous table created, both id_A and id_B would be unique values. I understand that id_A is forced to be unique by the
PRIMARY KEY (id_A) code, which is perfect (which also indexes it), however id_B isn't
Here is where I am confused. id_B will also be unique, however I am not sure how to force it to be unique in the table,and how to make the database create an index for it so that future queries that use SELECT on this table will have good preformance. I know I can't have two PRIMARY KEYS:
PRIMARY KEY (id_A)
PRIMARY KEY (id_B)
How might I go about making an index for id_B as well so that future queries happen efficiently?
You can add a UNIQUE INDEX on the column. While a table can only have one PRIMARY KEY, it can have as many UNIQUE INDEXes as you might need.
ALTER TABLE myTable
ADD UNIQUE INDEX `UI_myTable_idB` (`id_B` );
You can use the MySQL UNIQUE KEY for the column. This will force the values in the id_B column to be unique, but not use it as the primary key column. You can achieve it with this statement:
CREATE TABLE myTable (
id_A BIGINT NOT NULL,
id_B INT NOT NULL,
some_info varchar(255),
some_info2 varchar(255),
PRIMARY KEY (id_A),
UNIQUE KEY (id_b))
This will automatically index the column like you want it to. Primary keys and unique keys in a MySQL table are essentially the same, except a primary key cannot be NULL, and there can be only one primary key column (or combination of primary key columns). There can be any number of unique key columns.
Hello i have a table which has one primary key by the name of ImageID and i want to make another column
also primary key which is PropertyID means Composite Key
HERE IS THE CODE, but its showing this error for me "#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( PropertyID INT, ImageID INT primary key (PropertyID, ImageID) )' at line "
Also the ImageID is already primary key, but with varchar(15) specification.
Alter TABLE properties (
PropertyID INT,
ImageID INT,
primary key (PropertyID, ImageID)
);
Each table can only have 1 primary key. You can only have one primary key, but you can have multiple columns in your primary key.
Taken from W3Schools:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)
Here the only primary key is pk_PersonID but that have stated that pk_PersonID is made up of P_Id and LastName.
Unique Indexes may be what you're looking for. This means unique values are required and runs like an index in that it can speed up queries.
Try this:
First drop the existing primary key
ALTER TABLE properties
DROP PRIMARY KEY;
Then add composite key
ALTER TABLE properties
ADD PRIMARY KEY(imageID, propertyID);
As I understand you already have a table with one key, which looks like the following:
CREATE TABLE `common`.`properties` (
`PropertyID` VARCHAR(15) NOT NULL,
`otherColumn` VARCHAR(45) NULL,
PRIMARY KEY (`PropertyID`));
And now you want to add another PK column and change the type of existing PK column from char to INT. So you need to do it as following:
ALTER TABLE `common`.`properties`
CHANGE COLUMN `PropertyID` `PropertyID` INT NOT NULL ,
ADD COLUMN `ImageID` INT NOT NULL AFTER `otherColumn`,
DROP PRIMARY KEY,
ADD PRIMARY KEY (`PropertyID`, `ImageID`);
P.S. common is my schema name, you can use your own, or even skip it if your schema is default.
I am trying to alter a table which has no primary key nor auto_increment column. I know how to add an primary key column but I was wondering if it's possible to insert data into the primary key column automatically (I already have 500 rows in DB and want to give them id but I don't want to do it manually). Any thoughts? Thanks a lot.
An ALTER TABLE statement adding the PRIMARY KEY column works correctly in my testing:
ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;
On a temporary table created for testing purposes, the above statement created the AUTO_INCREMENT id column and inserted auto-increment values for each existing row in the table, starting with 1.
suppose you don't have column for auto increment like id, no, then you can add using following query:
ALTER TABLE table_name ADD id int NOT NULL AUTO_INCREMENT primary key FIRST
If you've column, then alter to auto increment using following query:
ALTER TABLE table_name MODIFY column_name datatype(length) AUTO_INCREMENT PRIMARY KEY
For those like myself getting a Multiple primary key defined error try:
ALTER TABLE `myTable` ADD COLUMN `id` INT AUTO_INCREMENT UNIQUE FIRST NOT NULL;
On MySQL v5.5.31 this set the id column as the primary key for me and populated each row with an incrementing value.
In order to make the existing primary key as auto_increment, you may use:
ALTER TABLE table_name MODIFY id INT AUTO_INCREMENT;
Yes, something like this would do it, it might not be the best though. You might wanna make a backup:
$get_query = mysql_query("SELECT `any_field` FROM `your_table`");
$auto_increment_id = 1;
while($row = mysql_fetch_assoc($get_query))
{
$update_query = mysql_query("UPDATE `your_table` SET `auto_increment_id`=$auto_increment_id WHERE `any_field` = '".$row['any_field']."'");
$auto_increment_id++;
}
Notice that the the any_field you select must be the same when updating.
The easiest and quickest I find is this
ALTER TABLE mydb.mytable
ADD COLUMN mycolumnname INT NOT NULL AUTO_INCREMENT AFTER updated,
ADD UNIQUE INDEX mycolumnname_UNIQUE (mycolumname ASC);
I was able to adapt these instructions take a table with an existing non-increment primary key, and add an incrementing primary key to the table and create a new composite primary key with both the old and new keys as a composite primary key using the following code:
DROP TABLE IF EXISTS SAKAI_USER_ID_MAP;
CREATE TABLE SAKAI_USER_ID_MAP (
USER_ID VARCHAR (99) NOT NULL,
EID VARCHAR (255) NOT NULL,
PRIMARY KEY (USER_ID)
);
INSERT INTO SAKAI_USER_ID_MAP VALUES ('admin', 'admin');
INSERT INTO SAKAI_USER_ID_MAP VALUES ('postmaster', 'postmaster');
ALTER TABLE SAKAI_USER_ID_MAP
DROP PRIMARY KEY,
ADD _USER_ID INT AUTO_INCREMENT NOT NULL FIRST,
ADD PRIMARY KEY ( _USER_ID, USER_ID );
When this is done, the _USER_ID field exists and has all number values for the primary key exactly as you would expect. With the "DROP TABLE" at the top, you can run this over and over to experiment with variations.
What I have not been able to get working is the situation where there are incoming FOREIGN KEYs that already point at the USER_ID field. I get this message when I try to do a more complex example with an incoming foreign key from another table.
#1025 - Error on rename of './zap/#sql-da07_6d' to './zap/SAKAI_USER_ID_MAP' (errno: 150)
I am guessing that I need to tear down all foreign keys before doing the ALTER table and then rebuild them afterwards. But for now I wanted to share this solution to a more challenging version of the original question in case others ran into this situation.
Export your table, then empty your table, then add field as unique INT, then change it to AUTO_INCREMENT, then import your table again that you exported previously.
You can add a new Primary Key column to an existing table, which can have sequence numbers, using command:
ALTER TABLE mydb.mytable ADD pk_columnName INT IDENTITY
I was facing the same problem so what I did I dropped the field for the primary key then I recreated it and made sure that it is auto incremental . That worked for me . I hope it helps others
ALTER TABLE tableName MODIFY tableNameID MEDIUMINT NOT NULL AUTO_INCREMENT;
Here tableName is name of your table,
tableName is your column name which is primary has to be modified
MEDIUMINT is a data type of your existing primary key
AUTO_INCREMENT you have to add just auto_increment after not null
It will make that primary key auto_increment......
Hope this is helpful:)
Well, you have multiple ways to do this:
-if you don't have any data on your table, just drop it and create it again.
Dropping the existing field and creating it again like this
ALTER TABLE test DROP PRIMARY KEY, DROP test_id, ADD test_id int AUTO_INCREMENT NOT NULL FIRST, ADD PRIMARY KEY (test_id);
Or just modify it
ALTER TABLE test MODIFY test_id INT AUTO_INCREMENT NOT NULL, ADD PRIMARY KEY (test_id);
How to write PHP to ALTER the already existing field (name, in this example) to make it a primary key? W/o, of course, adding any additional 'id' fields to the table..
This a table currently created - Number of Records found: 4 name VARCHAR(20) YES
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
This an end result sought (TABLE DESCRIPTION) -
Number of records found: 4
name VARCHAR(20) NO PRI
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
Instead of getting this -
Number of Records found: 5
id int(11) NO PRI
name VARCHAR(20) YES
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
after trying..
$query = "ALTER TABLE racehorses ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id)";
how to get this? -
Number of records found: 4
name VARCHAR(20) NO PRI
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
i.e. INSERT/ADD.. etc. the primary key INTO the first field record (w/o adding an additional 'id' field, as stated earlier.
No existing primary key
ALTER TABLE `db`.`table`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
;
Table already has an existing primary key'd column
(it will not delete the old primary key column)
ALTER TABLE `db`.`table`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
CHANGE COLUMN `prev_column` `prev_column` VARCHAR(2000) NULL ,
DROP PRIMARY KEY,
ADD PRIMARY KEY (`id`);
;
Note: column must be first for auto increment which is why the FIRST command.