autoincrement as primary key causing duplicate entries - php

I want an id and name to be primary key for my table. I want to increment id with every insert, so i set it to auto_increment. The problem is when i insert into table a new entry with same name, it inserts it with a new id and there are duplicate entries with same name and different ids. I don't want to search the table beforehand to see if there is any entry beforehand. Please help me how to correct this problem.

I think you have done something like this
CREATE TABLE table1
id unsigned integer autoincrement,
name varchar,
....
primary key (id,name)
This primary key does not select on unique name, because the autoincrement id will always make the key as a whole unique, even with duplicate name-fields.
Also note that long primary keys are a bad idea, the longer your PK, the slower inserts and selects will execute. This is esspecially bad on InnoDB, because the PK is included in each and every secondary key, ballooning your index files.
Change it to this
CREATE TABLE table1
id unsigned integer autoincrement primary key,
name varchar,
....
unique index `name`(name)

If you want it to be unique by name, you need to add a unique index on the name field, and then you can use the mysql syntax for on duplicate key: mysql reference for on duplicate key

You could apply a unique index to your name field, or if you're storing people, allow duplicate names.

Add UNIQUE(your_column_name) where you should replace your_column_name with the column in your database.

Related

Mysql duplicate row prevention [duplicate]

I want to add complex unique key to existing table. Key contains from 4 fields (user_id, game_id, date, time).
But table have non unique rows.
I understand that I can remove all duplicate dates and after that add complex key.
Maybe exist another solution without searching all duplicate data. (like add unique ignore etc).
UPD
I searched, how can remove duplicate mysql rows - i think it's good solution.
Remove duplicates using only a MySQL query?
You can do as yAnTar advised
ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY
OR
You can add a constraint
ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time)
But I think to not lose your existing data, you can add an indentity column and then make a composite key.
The proper syntax would be - ALTER TABLE Table_Name ADD UNIQUE (column_name)
Example
ALTER TABLE 0_value_addition_setup ADD UNIQUE (`value_code`)
I had to solve a similar problem. I inherited a large source table from MS Access with nearly 15000 records that did not have a primary key, which I had to normalize and make CakePHP compatible. One convention of CakePHP is that every table has a the primary key, that it is first column and that it is called 'id'. The following simple statement did the trick for me under MySQL 5.5:
ALTER TABLE `database_name`.`table_name`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
This added a new column 'id' of type integer in front of the existing data ("FIRST" keyword). The AUTO_INCREMENT keyword increments the ids starting with 1. Now every dataset has a unique numerical id. (Without the AUTO_INCREMENT statement all rows are populated with id = 0).
Set Multiple Unique key into table
ALTER TABLE table_name
ADD CONSTRAINT UC_table_name UNIQUE (field1,field2);
I am providing my solution with the assumption on your business logic. Basically in my design I will allow the table to store only one record for a user-game combination. So I will add a composite key to the table.
PRIMARY KEY (`user_id`,`game_id`)
Either create an auto-increment id or a UNIQUE id and add it to the natural key you are talking about with the 4 fields. this will make every row in the table unique...
For MySQL:
ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;
If yourColumnName has some values doesn't unique, and now you wanna add an unique index for it. Try this:
CREATE UNIQUE INDEX [IDX_Name] ON yourTableName (yourColumnName) WHERE [id]>1963 --1963 is max(id)-1
Now, try to insert some values are exists for test.

php MySql 2 column as index and 1 as another index?

I'm using php and i have a table that have 2 column of varchar , one is used for user identification, and the other is used for page name entry.
they both must be varchar.
i want to insert ignore data when user enter a page to know if he visited it or not, and i want to fetch all the rows that the user have been in.
fetch all for first varchar column.
insert if not exist for both values.
I'm hoping to do it in the most efficient way.
what is the best way to insert without checking with another query if exist?
what is the best way other then:
SELECT * FROM table WHERE id = id
to fetch when the column needed is varchar?
You should consider a normalized table structure like this:
CREATE TABLE user (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE page (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE pages_visted (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id INT UNSIGNED,
page_id INT UNSIGNED,
UNIQUE KEY (user_id, page_id)
);
INSERT IGNORE INTO pages_visted (user_id, page_id) VALUES (:userId, :pageId);
SELECT page_id FROM pages_visted WHERE user_id = :userId;
I think you want to implement a composite primary key.
A composite primary key tells MySQL that you want your primary key to be a combination of fields.
More info here: Why use multiple columns as primary keys (composite primary key)
I don't know of a better option for your query, although I can advise, if possible:
Define columns to be NOT NULL. This gives you faster processing and requires less storage. It will also simplify queries sometimes because you don't need to check for NULL as a special case.
And with variable-length rows, you get more fragmentation in tables where you perform many deletes or updates due to the differing sizes of the records. You'll need to run OPTIMIZE TABLE periodically to maintain performance.

How to avoid duplicate on insert of field values in mysql

Good day guys, I have a grade/score table in MySql that students record will be inserted into using php. I want to avoid a student having a score repeated for a term/period. What I mean is that a student cant have two(2) grades/scores for a subject(mathematics) in a term(periodOne) table. How do I accomplish this in MySql or php? here is how my table looks:
table periodOne (
id int AUTO_INCREMENT,
studentId int,
subjectId int,
score
)
Let me know if you need extra information. Thanks!!!!!!
you have to add a unique contraint in mysql like this : ALTER TABLE periodOne ADD CONSTRAINT uc_check UNIQUE(studentId, subjectId). You will also have to check with PHP that there is no existing row before to do your INSERT
You can declare the attribute as "Unique" by using UNIQUE CONSTRAINT for which you don't want duplicate value.
If your score are dependent on some other table also then you can use Composite Primary Key.

MYSQL- Create and store primary key in master and child table

I got stuck while insertion into database tables.
I have below tables.
I dont have any fields which can be make as Primary key.
Here "eme_request" and "eme_attachment" is master tables.
I want to know that how can I insert into tables ?
These tables(eme_request, eme_gf_relevent, eme_non_gf_relevent, eme_attachment) are getting insertion on one form request.
So I am not getting how to generate primary key in master table and how to insert into child table with that primary key as a Foreign key ?
In eme_request table REQ_ID (your PK) is type of varchar. If you can change it to INT and add flag AUTOINCREMENT, you will get automatically generated key.
If you can't change type of REQ_ID (you need it to be char), just add abstract PRIMARY_KEY int column and use it.
After inserting into table with autoincrement column you can receive assigned key with
https://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id so it can be used as FOREIGN KEY for other tables.

Why can't I insert the same ID into the 'id' column of my MySQL table?

I'm creating a messaging system and I'm trying to set it up so it will have a "conversation view" and so users can reply to a message. To do this I have to have a primary ID for each conversation in the table and then a separate unique ID for each message.
My problem is that when I try replying to a message I get this error:
Duplicate entry '98' for key 1
It looks like it isn't allowing me to use the same ID in a column, but I don't have a 'unique' thing set in the table AFAIK.
I also tried to drop the PRIMARY for the id column but got this error:
The message is:
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
I don't understand why it won't let me insert the same ID into the id column, because as you know I need an ID for each conversation.
The mysql_query that I'm using to insert the reply into the table is:
$sql = "INSERT INTO messages (id, message_id, to_user, message, subject, from_user, date, time, date_short)
VALUES ('$id', '$message_id', '$to', '$message', '$subject', '$user', '$date', '$time', '$date_short')";
mysql_query($sql) or die(mysql_error());
Thanks in advance!
Your primary key can not be repeated, otherwise it isn't so useful as a key, is it? The primary key must uniquely identify the record.
The reason you're getting the error is that the column is set to be auto-number. You have not added that column to a separate key, which is a requirement for auto-number columns in MySQL.
Add it to a key/index with that column first, then remove the PK attribute. Make sure you have some PK in the table.
You can't have auto_increment without a key
I suspect you have AUTO_INCREMENT setup on your id field. If this is the case, then the values in the id column must be unique.
Either remove the AUTO_INCREMENT attribute on that column (by redefining the column without AUTO_INCREMENT via an ALTER TABLE command), or don't specify the id value in your INSERT statement.
First, untick AUTO_INCREMENT option on your column and as the second step, try to drop the index again
PRIMARY KEYs are also unique. auto_increment columns must be primary keys. You can't drop PRIMARY KEY from a column without making it not auto_increment.
However, I don't think you should change your table like this. You should keep your IDs and either create a new table with the data you need to update, or use UPDATE instead of INSERT.
Columns with primary keys can't have duplicates, otherwise they lose their uniqueness. MySQL will prevent same values. Having to alter primary key vales is also bad news. You may want to re-approach what you're doing and possibly create more tables.

Categories