Let's say I have a table with an integer column called ID being a primary key. It is unique and not-null, but we cannot guarantee it being sequential without gaps. I.e. we may have rows with ID = 1,2,6,7,8 and we do not have rows with ID 3,4,5 etc etc.
This is why we cannot just generate a random number and get a row with that corresponding ID.
Also we want all rows to have equal chance of being selected, so b/c of the gaps in ID values we cannot use simple approach with random number in 0 to max(id) range
The number of rows in the table is not known either.
How can I select a random row from that table?
Here is the table schema:
CREATE TABLE IF NOT EXISTS `test_data` (
`id` int(10) unsigned NOT NULL,
`create_date` datetime DEFAULT NULL,
`text_1` varchar(255) NOT NULL DEFAULT 'BMqFXUslYnGsYsPxHTtZVbcwnEWFmSXxTAUV9YxXXDH5ClUEUO8kFz0cW1xC3o9aMSwabnEr43W23KZnKvrk8PHEJv18SU5JHTH72sLTtleitBJBIWmIpul7LtuYOpc4iRDqEAT80UeG7L2l4r1pr2jEMW7222reAOuIcBIUcsH9LYlojeQjVkc9ZhYXgnN3xRGHLJ3L0MGoXO4GHttEv053DqkkKYEye34bpGI2tJ0IE9M8BIFf2u08jB50nhD',
`text_2` varchar(255) NOT NULL DEFAULT 'hoA6tWi8AEcikkJM50Mz800PGTUKNnyj3OCKhyJ4ExaJf6bYbqXlNWo4y0XXXo7HuvsNgYWnn16211RbKDesQ852QA33s1eni4pBoraEs3YiV0W69yMY7Nf0pvQI198HUVKYPWk9zpK38PDphtPJXO2z5Wb8mbBN0gN8iK5xzUQQDwoAJlO3Z8xXn2OWyVjKswRbZNKW6l0tvn0zN4S4BoR9gkN7s4Ov9tTGeF4uwWYhPEs0WsDqatMjmbnMQmC'
) ENGINE=InnoDB;
ALTER TABLE `test_data`
ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
Have you tried RAND()?
SELECT * FROM `test_data` ORDER BY RAND() LIMIT 1;
Related
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 ;
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.
I have a MySql table created like this:
CREATE TABLE `sourcelinks` (
`idSourceLinks` int(10) unsigned NOT NULL AUTO_INCREMENT,
`SrcId` int(11) NOT NULL DEFAULT '-1',
`LinkId` int(11) DEFAULT '-1',
`ImageId` int(11) DEFAULT '-1',
`DownloadId` int(11) DEFAULT '-1',
`VideoId` int(11) DEFAULT '-1',
PRIMARY KEY (`idSourceLinks`),
UNIQUE KEY `idSourceLinks_UNIQUE` (`idSourceLinks`),
UNIQUE KEY `UniqueCombination` (`SrcId`,`LinkId`,`ImageId`,`DownloadId`,`VideoId`)
) ENGINE=InnoDB AUTO_INCREMENT=491 DEFAULT CHARSET=latin1;
As you can see I have a combined UNIQUE INDEX over SrcId, LinkId, ImageId, DownloadId, and VideoId. Now my understanding is that if SrcId and LinkId have the same values as another row then a DUPLICATE INSERT exception would be thrown. That would be the same as SrcId and ImageId, or SrcId and DownloadId etc.
QUESTIONS:
So, why does it not actually work? I am getting multiple columns with the same values, that is multiple SrcId =1 and LinkId = 1 with the other columns in the index being null?
And how do i fix it so that each row can only have unique values attached for the columns
A unique index on (SrcId, LinkId, ImageId, DownloadId, VideoId) only means that a given combination of values of all five of these columns must be unique. It does not that more than one record cannot have the same values for SrcId and LinkId. If you require that, the unique index should be on (SrcId, LinkId). If this were the original intention of the five column unique index, then perhaps remove it and replace it with the two column version.
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.
If I create a table with the following syntax,
CREATE TABLE IF NOT EXISTS `hashes` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`hash` binary(20) NOT NULL,
PRIMARY KEY (`id`,`hash`),
UNIQUE KEY (`hash`)
) ENGINE=InnoDB ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE = 4 AUTO_INCREMENT=1
PARTITION BY KEY(`hash`)
PARTITIONS 10;
And insert queries with the following syntax
INSERT INTO hashes (hash) VALUES ($value) ON DUPLICATE KEY UPDATE hash = hash
Then the auto increment column works as expected both if the row is inserted or updated.
Although creating the table without the partition like below and inserting with the query above the auto increment value will increase by 1 on every update or insert causing the A_I column to be all over place as the query could do 10 updates and then 1 insert causing the column value to jump 10 places.
CREATE TABLE IF NOT EXISTS `hashes` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`hash` binary(20) NOT NULL,
PRIMARY KEY (`id`,`hash`),
UNIQUE KEY (`hash`)
) ENGINE=InnoDB AUTO_INCREMENT=1;
I understand why the value increases on an update with INNO_DB but I do not understand why it doesn't when the table is partitioned?
you cannot change that, but you can try something like this:
mysql> set #a:= (select max(id) + 2 from hashes);
mysql> insert into hashes (id) values ($value) on duplicate key update id=#a;
NOTE: the partitions change a little bit after mysql 5.6, which version do you have?