How to use more than 1 auto-increment column in MySQL - mysql

I want to create a table name Users where I should have have columns User, cookieID, sessionID, Geo and then I want to first three columns to have some random unique value assigned automatically. I tried to make all three columns AUTO_INCREMENT with User column PRIMARY and 'cookieIDandsessionIDcolumnUNIQUE`. The SQL code is:
CREATE TABLE `users` ( `User` VARCHAR(20) NOT NULL AUTO_INCREMENT ,
`cookieID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`sessionID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`Geo` VARCHAR(30) NULL DEFAULT NULL ,
PRIMARY KEY (`User`), UNIQUE (`cookieID`), UNIQUE (`sessionID`), UNIQUE (`Geo`));
But, it did not work because only one column can be declared as AUTO_INCREMENT which must be PRIMARY.
What is the another approach to do this?

Since the auto-increment cannot be applied to multiple to rows and there no option for sequence in MySQL. You can use triggers for the unique update of the row with datetime.
Change to table creation to be of single auto-increment row.
CREATE TABLE `users` ( `User` VARCHAR(20) NOT NULL,
`cookieID` INT(20) NULL DEFAULT NULL,
`sessionID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`Geo` VARCHAR(30) NULL DEFAULT NULL,
PRIMARY KEY (`User`), UNIQUE (`cookieID`), UNIQUE (`sessionID`), UNIQUE (`Geo`));
Create a trigger on the same table as below. You can set the unique values under the SET for as many column as you want.
CREATE DEFINER=`root`#`localhost` TRIGGER `users_BEFORE_INSERT` BEFORE INSERT ON `users` FOR EACH ROW BEGIN
SET
NEW.cookieID = (SELECT curdate()+curtime());
END
Now when you insert into the table as below.
insert into `users`(`User`) values("test");
You table looks like this.
User cookieID sessionID Geo
test 20315169 0 NULL

If the value which are auto incrementing, you wanna keep both values the same. Then copy the value of one column to another during insertion time of new value.

Related

Specific field parameter when creating a table MySQL

I'm using MySQL Workbench.
I would like to create a table named courseInfo and I want to put a column named moduleCode in it, but I want it to always be similar in format: CFSM H0000 where the four zeros are a number that increases starting with 0000.
For example:
CFSM H0001
CFSM H0002
[..]
You cannot auto-increment character type columns in MySQL, as auto-increment is only possible on integer type columns. One (alphanumeric) auto-incrementing moduleCode column would therefore not be possible. However, you could try splitting up the moduleCode into two columns, for example like so:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
KEY (`id`)
) AUTO_INCREMENT = 0;
Where prefix could for example be "CFSM H" and id could be 0001
Then, upon executing SELECT statements, you could merge the prefix column with the id column into a moduleCode column with CONCAT, e.g.:
SELECT CONCAT(`prefix`, `id`) as `moduleCode` FROM `courseInfo`;
An alternative approach (from MySQL version 5.7 and up) seems to be the use of a generated column, for example:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
`moduleCode` CHAR(10) AS (CONCAT(`prefix`, `id`)),
KEY (`id`)
) AUTO_INCREMENT = 0;
However, the above example of a generated column would not work, because moduleCode is dependent on an auto-increment column, and the auto-increment is not executed yet at the time the generated column is computed. See also: https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html. It would throw an ER_GENERATED_COLUMN_REF_AUTO_INC error.
You could therefore use the first solution, or try to add moduleCode as a column and use an AFTER INSERT trigger to update its value:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
`moduleCode` CHAR(10),
KEY (`id`),
UNIQUE KEY `unique_index` (`prefix`,`id`)
) AUTO_INCREMENT = 0;
DELIMITER //
CREATE TRIGGER `addModuleCode` AFTER INSERT ON `courseInfo`
FOR EACH ROW
BEGIN
UPDATE `courseInfo` SET `moduleCode` = CONCAT(NEW.`prefix`, NEW.`id`) WHERE `prefix` = NEW.`prefix` AND `id` = NEW.`id`;
END;//
DELIMITER ;

What is wrong with my JOINs?

So I am incredibly new to MySQL and I am struggling every step of the way to learning it. I am supposed to create a small database that can be about anything for my class assignment. I have the tables created but I am trying to figure out how to correctly JOIN them together.
Here is the code I currently have for it:
CREATE TABLE `monster` (
`monster_id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`name` VARCHAR(30) NULL DEFAULT NULL,
`hitpoints` TINYINT NULL DEFAULT NULL,
`armorclass` TINYINT NULL DEFAULT NULL,
PRIMARY KEY (`monster_id`)
);
CREATE TABLE `monster_size` (
`monster_id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`size_id` INTEGER NULL DEFAULT NULL,
PRIMARY KEY (`monster_id`)
);
CREATE TABLE `size` (
`size_id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`size` VARCHAR(15) NULL DEFAULT NULL,
PRIMARY KEY (`size_id`)
);
ALTER TABLE `monster_size` ADD FOREIGN KEY (monster_id) REFERENCES `monster` (`monster_id`);
ALTER TABLE `monster_size` ADD FOREIGN KEY (size_id) REFERENCES `size` (`size_id`);
/* Here is where I am trying to get the joining to happen */
SELECT name,hitpoints,size
FROM monster m
JOIN size s ON (m.monster_id=s.size_id)
JOIN monster_size ms ON (s.size_id=ms.size_id);
You're not joining the tables in the correct way. You'll want to join the monster table with the monster_size junction table, and then the size table with the monster_size table, like this:
SELECT name,hitpoints,size
FROM monster m
JOIN monster_size ms ON m.monster_id = ms.monster_id
JOIN size s ON ms.size_id = s.size_id
In your current query you're trying to match the id from the size table with the id from the monster table, but those two tables doesn't have any direct relation, so you need to use the monster_size table to connect them.
You are using a linking table monster_size. This means that you are creating an m to n relation. Can a monster really have several sizes at the same time? Because now, a size can be linked to several monsters, but a monster can also be linked to several sizes through this linking table.
Also this linking table should not have an auto increment column.
But probably you just want to link one size to a monster at a time. Forget the monster_size table. Instead add a size_id column to the monster table (no auto increment). Probably the set of possible sizes will not change anyway, so you could drop the auto increment in the size table as well and add well defines IDs "manually".
New table structure
DROP TABLE IF EXISTS `monster`;
CREATE TABLE `monster` (
`monster_id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
`name` VARCHAR(30) NULL DEFAULT NULL,
`hitpoints` TINYINT NULL DEFAULT NULL,
`armorclass` TINYINT NULL DEFAULT NULL,
`size_id` INTEGER NULL DEFAULT NULL,
PRIMARY KEY (`monster_id`)
);
DROP TABLE IF EXISTS `size`;
CREATE TABLE `size` (
`size_id` INTEGER NULL DEFAULT NULL,
`size` VARCHAR(15) NULL DEFAULT NULL,
PRIMARY KEY (`size_id`)
);
ALTER TABLE `monster` ADD FOREIGN KEY (size_id) REFERENCES `size` (`size_id`);
INSERT INTO size (size_id, size) VALUES (1, 'small');
INSERT INTO size (size_id, size) VALUES (2, 'big');
INSERT INTO size (size_id, size) VALUES (3, 'huge');
INSERT INTO monster(name, hitpoints, size_id) VALUES ('Tester', 10, 1);
Now, your query goes like this
SELECT m.name, m.hitpoints, s.size
FROM
monster m
LEFT JOIN size s
ON (m.size_id = s.size_id);
Also use a left outer join, in case a size_id is null in the monster table.

MySQL Auto increment not incrementing

I've created a table with 3 columns: postID, userID, and comment.
I have the postID as the primary key, and I am trying to make this auto-increment every time I add a new row to the table.
INSERT INTO CommentTable (postID, userID, comment) VALUES (DEFAULT, "test", "test")
When I run this query, it will run OK once but then when I run it again I get "1062 - Duplicate entry '0' for key 'PRIMARY'".
How do I properly set up an auto-increment primary key?
Here is the table structure:
DROP TABLE IF EXISTS `CommentTable`;
CREATE TABLE `CommentTable` (
`postID` int(10) NOT NULL,
`userID` varchar(10) NOT NULL,
`comment` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`commentID`)
)
No need to put the field postID
INSERT INTO CommentTable (userID, comment) VALUES ("test", "test")
Edit your table as:
CREATE TABLE `CommentTable` (
`postID` int(10) NOT NULL AUTO_INCREMENT,
`userID` varchar(10) NOT NULL,
`comment` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`postID`)
)
Recently I had the same issue where Auto Increment was not saved. It failed every time I tried to save it. My problem was that I had a record where the value was 0 instead of 1, so I updated that record value to a non-zero value, then tried saving the Auto Increment, and it worked.
The zero(0) value in the Primary Index field was causing the ALTER tablename to fail. Once it worked, I put the value back to 0.

alter table statment to insert duplicate into another table

I have a table in which there is a column name with SP varchar(10) NOT NULL. I want that column always to be unique so i created unique index on that column . My table schema as follows :
CREATE TABLE IF NOT EXISTS `tblspmaster` (
`CSN` bigint(20) NOT NULL AUTO_INCREMENT,
`SP` varchar(10) NOT NULL,
`FileImportedDate` date NOT NULL,
`AMZFileName` varchar(50) NOT NULL,
`CasperBatch` varchar(50) NOT NULL,
`BatchProcessedDate` date NOT NULL,
`ExpiryDate` date NOT NULL,
`Region` varchar(50) NOT NULL,
`FCCity` varchar(50) NOT NULL,
`VendorID` int(11) NOT NULL,
`LocationID` int(11) NOT NULL,
PRIMARY KEY (`CSN`),
UNIQUE KEY `SP` (`SP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10000000000 ;
Now i want that if anybody tries to insert duplicate record then that record should be inserted into a secondary table name tblDuplicate.
I have gone through this question MySQL - ignore insert error: duplicate entry but i am not sure that instead of
INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200;
can i insert duplicate row into another table ?
what changes needed to be done in main table scheme or index column ?
**Note : Data will be inserted by importing excel or csv files and excel files generally contains 500k to 800 k records but there will be only one single column **
I believe you want to use a trigger for this. Here is the MySQL reference chapter on triggers.
Use a before insert trigger. In the trigger, check if the row is a duplicate (maybe count(*) where key column value = value to be inserted). If the row is a duplicate, perform an insert into your secondary table.

use ON DUPLICATE KEY for table that have two primary key

I have a table with 2 primary keys(user_id,post_id)
I want to insert row only if table havn't a row with this user id and post id
And if previous data exist for this keys , only that row update with the new data
I wrote this query:
INSERT INTO trust_list(`user_id`,`post_id`,`post_per`,`comment_per`,`cat_per`)
VALUES (7,1,'000','000','000')
ON DUPLICATE KEY UPDATE `post_per`='000',`comment_per`='000',`cat_per`='000'
For example if this row exist in the table:
user_id:5
post_id:1
post_per:001
comment_per:111
cat_per:101
Then ,when i execute the above query , mysql update this row,only because post_id of this row is "1"
Whereas mysql should not update this row .
I don't understand what's the problem.
DESC trust_list
result of above query is:
Field Type Null Key Default Extra
user_id int(11) NO PRI NULL
post_id int(4) NO PRI NULL
post_per tinytext YES NULL
comment_per tinytext YES NULL
cat_per tinytext YES NULL
=================
Thanks to all of my friends
When i decide to drop table and ceate it again ,I get an export from this table
and review the .sql file,i see this:
CREATE TABLE IF NOT EXISTS `trust_list` (
`user_id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`post_per` tinytext COLLATE utf8_estonian_ci ,
`comment_per` tinytext COLLATE utf8_estonian_ci ,
`cat_per` tinytext COLLATE utf8_estonian_ci ,
PRIMARY KEY (`idea_id`,`user_id`),
UNIQUE KEY `idea_id` (`idea_id`)
)
apparently , problem is from the UNIQUE KEY ,I remove it from file ,and then drop trust_list table ,and then import .sql file
So with this ,my problem solved
Thanks again
There is something wrong with your table schema.
Assuming that your schema defined something like this
CREATE TABLE trust_list(
`user_id` int,
`post_id` int,
`post_per` varchar(12),
`comment_per` varchar(12),
`cat_per`varchar(12),
PRIMARY KEY(`user_id`, `post_id`)
);
here is SQLFiddle that demonstrates that your INSERT statement works on it just fine.
Consider to show your CREATE TABLE statement to help you find the problem, or just change PK as showed.
I think your problem is your understanding of primary key. You can't have two primary keys in the table, only one. What you have probably is a primary key that consists of two columns. In that case you only get a key violation when both columns match.
Solution:
Introduce unique indices for both columns. Or - better - change the primary key to be only one of the two columns and set the other column to have a unique index.
Thanks to peterem here is the sqlfiddle with my solution.