Mysql conditional insert(With the combined primary key) - mysql

I have the table with following structure
id -- auto increment
name -- unique
group -- integer
Primary key(name,group)
I do not want to add the element with the same name and group values.
(i.e ("test",1) and ("test",1) should not be inserted.... and
("test",1),("test",2) can be inserted).
I want to insert a value if not exist .. I checked the Link.
Using the above link it is possible to do the operation , but the problem is it only checks the name as key not combined with group (i.e Insertion of the values("test",1) and ("test",2) is not happening)
How can i do this.

I think problem with name column unique ,please remove unique constraint on name column and try INSERT IGNORE INTO yourTable(name,group)values("test",2)

If your primary key is a composite of name and group
You can do INSERT IGNORE
INSERT IGNORE INTO yourTable
SET name = 'test',
group = 1;
As long as both of them are part of your primary key, this should check for their combination

Related

MySQL | Update records insert of insert if field exists

I have a table with three fields:
Auto increment integer (primary key)
String which should be unique
integer containing a value which is not unique
See picture here:
enter image description here
The value for the integer field does not need to be unique.
My problem:
I pull data from an API and insert the string and third field (integer) into the table. At the moment i am truncating the table and inserting again to avoid duplicates. How do I do it so if the string is existing, it just updates the third field (integer), if it does not exist it will insert the row as normal.
I am aware of the ON DUPLICATE KEY technique however my 'key' is the primary key and it is the string field that i want to check for duplicates.
If the string field should be unique, then declare it as unique:
alter table add constraint unq_table_string unique (string);
Then, on duplicate key will find a match when this constraint is also violated.
You can try the below query -
ALTER IGNORE TABLE `your_table`
ADD UNIQUE INDEX (`hash_name` );
This will add unique index to your table and remove all duplicate hash_name and will make sure that no duplicate hash_name being inserted in future.

How add unique key to existing table (with non uniques rows)

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.

Primary Key in SQL - Default value

I am working from this database, its one of the first I have tried building:
http://sqlfiddle.com/#!2/38ef8
When I try to add this line:
Insert Into country (name) values ('US');
It says Field 'id' doesn't have a default value. Am I doing my primary key correctly? I have seen people using "auto_incrment" on their primary key like this example:
http://sqlfiddle.com/#!2/c807a/2
Is that what I should be using?
If you didn't specify PRIMARY KEY column as AUTO_INCREMENT then you have to give values manually, for example:
INSERT INTO Country(id, name) values(1, 'US');
It's up to you wheter use AUTO_INCREMENT or not. There are many reasons to do it and many not to do it:
Pros and Cons of autoincrement keys on "every table"
Should each and every table have a primary key?
there are the properties of PRIMARY key
1 : cant be NULL
2 : cant be duplicate
now when you select AUTO_INCREMENT , every time you use the query
Insert Into country (name) values ('US');
it automatically generates a number incrementing the highest value existing in the table for the primary key column
but when you do not set the primary key as AUTO_INCREMENT ,
Insert Into country (name) values ('US');
this query will enter NULL values in every column for the row except the given column
in that case your PRIMARY_KEY also gets a null value
which clearly contradicts with the definition of PRIMARY_KEY .
that is why you get the error
I hope the explanation serves
If you have not set your primary key as auto increment, you will have to insert that manually in your queries.
The primary key should be set to AUTO_INCREMENT, if it is not so, you will have to set that manually.
Although you can still insert with specific values after setting the primary key to AUTO_INCREMENT provided the key is not already existing :D

MySQL INSERT only if two fields don't match

I have 6 fields with the primary as ID and is set to auto_increment. I want to INSERT a new row if DATE and FROM do not match. I was thinking of REPLACE INTO or ON DUPLICATE KEY UPDATE but from what I know I have to have one of them as my Primary? I don't care how its done I just need some help with a query that would work.
ID
DATE
STORE
TOTAL
NPS
FROM
What you need is a unique index composed of both the DATE and FROM fields.
ALTER TABLE table ADD UNIQUE INDEX(DATE, FROM);
Then you can use this type of query:
INSERT IGNORE INTO table (columns) VALUES (...)
The IGNORE statement will skip any INSERT that would otherwise cause a duplicate key error.

MySQL on duplicate key on a non-unique field

I have a table containing all sort of parameters.
The structure of the table is : id, object_id, param_name, param_value
The following code works, but it appends results instead of updating them.
The fact is that I can't use ON DUPLICATE KEY because my fields are non-uniques (except for id of course)
INSERT INTO `params_table` (`object_id`, `param_name`, `param_value`)
SELECT
A.id AS my_object_id,
'XYZ' AS my_param_name,
IF(TMP.abc IS NULL,0,1) AS my_param_value
FROM
ref_table AS A
LEFT JOIN tmp_table AS TMP ON TMP.abc = A.abc
ON DUPLICATE KEY
UPDATE `param_value` = IF(TMP.abc IS NULL,0,1);
The ON DUPLICATE KEY clause does not only work on the primary key:
If you specify ON DUPLICATE KEY
UPDATE, and a row is inserted that
would cause a duplicate value in a
UNIQUE index or PRIMARY KEY, an UPDATE
of the old row is performed
So unless I'm missing something obvious you simply need to create a unique index on the column combination you want to make unique:
ALTER TABLE params_table
ADD UNIQUE unique_object_param(object_id,param_name);