I have a table that I want to have an id that will auto increase itself but not be primary or unique.
Is this possible?
You should really create another table, in that case.
E.g.
CREATE TABLE `Calls` (
`Id` INT(10) AUTO_INCREMENT,
`From` VARCHAR(100) NOT NULL,
`To` VARCHAR(100) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=INNODB;
CREATE TABLE `CallHistory` (
`Id` INT(15) AUTO_INCREMENT,
`CallId` INT(10) NOT NULL,
`Text` VARCHAR(255) NOT NULL,
PRIMARY KEY (`Id`),
KEY `CallHistory_Calls_idx` (`CallId`),
CONSTRAINT `CallHistory_Calls`
FOREIGN KEY (`CallId`)
REFERENCES `calls` (`Id`)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=INNODB;
Here's a demo on SQLFiddle.
A benefit of this is that if you delete a row from Calls, the rows in CallHistory will also be deleted.
Running this query:
SELECT `Calls`.`Id`,
`Calls`.`From`,
`Calls`.`To`,
`CallHistory`.`Text`
FROM `Calls`, `CallHistory`
WHERE `Calls`.`Id` = `CallHistory`.`CallId`;
Gives results something like this:
This should work:
id int NOT NULL AUTO_INCREMENT
Anyway I don't see how it wouldn't stay unique unless you update existing values later
Yes, you need to set auto_increment constraint:
CREATE TABLE `test` (
`testID` int(11) NOT NULL, //primary key here
`testInc` int(11) NOT NULL AUTO_INCREMENT, //here is your non-primary auto increment column
PRIMARY KEY (`testID`),
KEY `testInc` (`testInc`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
and if you want this to be unique also then you may add unique constraint:
ALTER TABLE `test` ADD CONSTRAINT ux_unique_constraint UNIQUE `testInc`
Related
Assuming I am inserting rows in a MySQL table with a constraint
CREATE TABLE `parent` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
;
CREATE TABLE `child` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`id_parent` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
INDEX `FK_parent_child` (`id_parent`),
CONSTRAINT `FK_parent_child` FOREIGN KEY (`id_parent`) REFERENCES `parent` (`id`),
)
ENGINE=InnoDB
;
Then when I do an insert in the child table without the entry in the parent table:
INSERT INTO child (id, id_parent) VALUES (1, 1);
I get the following error:
Cannot add or update a child row: a foreign key constraint fails (`...`.`child`, CONSTRAINT `FK_parent_child` FOREIGN KEY (`id_parent`) REFERENCES `parent` (`id`))`
But is there a way to retrieve the value of the insert-failed row, aka 1 here? Because when I insert thousands of rows at the same time, it would be very useful to get the failed one.
I would like a fully-MySQL way, but a PHP way would work too in my case.
This is how my table looks like.
CREATE TABLE `answers` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`basicinfo_id` INT(11) NOT NULL,
`question_id` INT(11) NOT NULL,
`answer` INT(11) NOT NULL,
PRIMARY KEY (`id`),
INDEX `question_id` (`question_id`),
INDEX `basicinfo_id` (`basicinfo_id`),
CONSTRAINT `basicinfo_id` FOREIGN KEY (`basicinfo_id`) REFERENCES `basic_info` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT `question_id` FOREIGN KEY (`question_id`) REFERENCES `questions` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION) COLLATE='latin1_swedish_ci' ENGINE=InnoDB AUTO_INCREMENT=3383;
This is how the data can look like
I want to update the answers if they already exist for "basicinfo_id".
OR
If I change the answer for question_id 1, 2 and 3. How can i upsert the data.?
I have tried this query but it doesn't update the result.
INSERT INTO answers (basicinfo_id, question_id, answer) VALUES('98', 1, '1'),('98', 2, '1'),('98', 3, '1'),('98', 4, '1'),('98', 5, '1') ON DUPLICATE KEY UPDATE basicinfo_id = 98;
I have defined a composite unique key now and this is how it looks like but it still didn't work.
CREATE TABLE `answers` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`basicinfo_id` INT(11) NOT NULL,
`question_id` INT(11) NOT NULL,
`answer` INT(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `basicinfo_id_question_id` (`basicinfo_id`, `question_id`),
INDEX `question_id` (`question_id`),
INDEX `basicinfo_id` (`basicinfo_id`),
CONSTRAINT `basicinfo_id` FOREIGN KEY (`basicinfo_id`) REFERENCES `basic_info` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT `question_id` FOREIGN KEY (`question_id`) REFERENCES `questions` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB AUTO_INCREMENT=3718;
Your ON DUPLICATE KEY UPDATE basicinfo_id = 98; is malformed
Try this :
ON DUPLICATE KEY UPDATE 'answer' = VALUES('answer');
If a unique key already exists it will update the answer field
I am trying to create foreign key in one of my table but i am getting this error can you help with this
CREATE TABLE IF NOT EXISTS `albums` (
`id` smallint(5) unsigned NOT NULL,
`url` mediumtext NOT NULL,
`year` mediumint(9) NOT NULL,
`album_name` varchar(150) NOT NULL,
`album_cover` text NOT NULL,
`tracks_id` text NOT NULL,
`category` tinyint(4) NOT NULL,
`reciter` tinyint(4) NOT NULL,
`keywords` varchar(300) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
Foreign Key Table Structure
CREATE TABLE IF NOT EXISTS `album_likes` (
`album_id` int(5) NOT NULL,
`likes` int(11) NOT NULL,
`dislikes` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now what i did to make this foreign key is that i went to the structure of this table in phpmyadmin and then add constraint name select the columns
Here is the query
ALTER TABLE `album_likes` ADD CONSTRAINT `album_like_fk` FOREIGN KEY (`album_id`) REFERENCES `mp3script`.`albums`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
The output i got
1215 - Cannot add foreign key constraint
A foreign key requires an index on the column you are referencing, in this case albums.id.
Add the index:
CREATE INDEX ids_nn_1 on albums(id);
And you create foreign key should work
this table is already work fine
create table posts (
id bigint(20) unsigned not null auto_increment,
title varchar(200) not null,
content text,
mdesc varchar(340),
pdate timestamp not null default current_timestamp,
lupdate timestamp not null default '0000-00-00 00:00:00',
perma varchar(120) not null,
cat_id smallint(5) unsigned not null,
user_id int(11) unsigned not null,
views int(11) unsigned not null default 0,
status tinyint(1) unsigned not null default 0,
primary key (id),
unique key (title,cat_id),
foreign key (cat_id) references category (id) on delete restrict on update cascade,
foreign key (user_id) references users (id) on delete cascade on update cascade
) engine=innodb default charset=utf8;
but i dont know why i cant query viewers table i dont know why
create table viewers (
id int(11) unsigned not null auto_increment,
post_id bigint(20) unsigned not null,
primary key (id),
foreign key (post_id) references posts (id) on delete cascade
) engine=innodb default charset=utf8;
please help :)
Please try removing fks
Most commonly it is because of different properties.
Check
if id of post table is having same properties as of this? (here bigint)
Other possibilities could be
it isn't innodb engine for other table.
Names of fks are not unique
I have two tables- users and language with a foreign key link of their primary key 'id'.
I have checked that the type is innoDB for the tables. I have delete- restrict and update -cascade.
This insert query, inserts it into the language table: (it can be more than one row which is added as the form has dynamic clickevent button)
if(empty($_SESSION['user_id'])) { // user not logged in; redirect to somewhere else }
$sql_insert = "INSERT into `language`
(`native`,`other`,`other_list`,`other_read`, `other_spokint`
,`other_spokprod`,`other_writ` )
VALUES
('$native','$other','$other_list','$other_read','$other_spokint','$other_spokprod',
'$other_writ') ";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
}
This is the full error:
Insertion Failed:Cannot add or update a child row: a foreign key constraint fails
(`members`.`language`, CONSTRAINT `language_ibfk_1` FOREIGN KEY (`id`)
REFERENCES `users` (`id`))
Any help would be appreciated!
Table structure for table language:
CREATE TABLE IF NOT EXISTS `language` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`native` varchar(30) NOT NULL,
`other` varchar(30) NOT NULL,
`other_list` varchar(9) NOT NULL,
`other_read` varchar(9) NOT NULL,
`other_spokint` varchar(9) NOT NULL,
`other_spokprod` varchar(9) NOT NULL,
`other_writ` varchar(9) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
RELATIONS FOR TABLE `language`:
`id`
`users` -> `id`
You have to use a structure like this:
create table users (
id int not null auto_increment,
<additional fields>,
primary key (id)
) ENGINE=InnoDB;
create table language(
id int not null auto_increment,
user_id int not null,
<additional fields>,
primary key (id),
foreign key (user_id) references users(id) on delete restrict on update cascade
) ENGINE=InnoDB;