How to make unique combination of columns values? - mysql

I have a table with data like this:
id | link | name | date
1 aa bob 1
1 aa tom 2
1 bb tom 3
2 cc lora 4
It means I can have not unique values in any column but I CAN'T have the same row with identical id link name (date doesn't matter). This is the example what I can't have:
id | link | name | date
1 aa bob 1
1 aa bob 2
I tried to:
ALTER TABLE table ADD UNIQUE KEY `uk_id_link_name` (id, link, name);
also:
ALTER TABLE `table` ADD UNIQUE `unique_index`(`id`, `link`, `name`);
But it gives me an error:
Duplicate entry
How to make unique rows (combination of columns values which is not unique)?
EDIT: I don't want to delete duplicates from table.

Your table already violates the unique constraint. So you need to get rid of the offending values.
You can delete all but the earliest date:
delete t
from t join
(select id, link, name, min(date) as mindate
from t
group by id, link, name
) tt
using (id, link, name)
where date > mindate;
When the data is compatible, you can add the unique constraint.
Note: back up/make a copy of the table before doing this, so you don't lose data that you might really need.

The correct syntax for SQL Server should be the next:
ALTER TABLE TableName ADD CONSTRAINT ConstraintName UNIQUE (id, link, name)
But before create the constraint, of course you should ensure that there are not existing rows braking the constraint, for example using this query:
SELECT id, link, name, COUNT(*)
FROM TableName
GROUP BY id, link, name
HAVING COUNT(*) >= 2
This query returns the duplicates grouping by the three fields: id, link, name
If the query returns rows, you have to solve these duplicates before create the unique constraint.

Related

SQL adding in table rows with same id and different second id

I have a databasw that has 2 columns.
First is category id, the second is group id.
Both are primary.
And i need to add to the table to the same category id some rows with group id 1 and 2.
I mean all the categories need to have groups 1,2,3
INSERT INTO `ps_category_group` (`id_category`, `id_group`)
SELECT `id_category`, 2 FROM (
SELECT DISTINCT `id_category`,`id_group` From `ps_category_group`) as x;
gives me
1062 - Duplicate entry '2-2' for key 'PRIMARY'
You are selecting values from the same table for inserting into the table. Then you are asking why you are getting primary key violations? Of course you are; that is exactly what your query is doing.
Based on the description, you seem to want:
INSERT INTO `ps_category_group` (`id_category`, `id_group`)
SELECT `id_category`, 2
FROM `ps_category_group`
ON DUPLICATE KEY UPDATE id_category = VALUES(id_category); -- This does nothing if the value already exists in the table

Mysql : insert into select && where not exists

I need to insert some data in a table named ‘queue’ which is a patient queue in a particular date . Two fields data will be inserted .Two fields name are ‘PatientID’ and ‘Visiting Date’. Table ‘queue' like
QueueID | PatientID | Visiting_date |
-------------|-------------------|-------------------------|
1 | 4 | Current date |
table:queue
But while inserting the record there are two conditions :
Condition 1 : patitentID comes from patient table (given below)
Condition 2 : one record will be inserted to ‘queue’ table if it does not exist to prevent repeatation.ie PatientID=4 will not be inserted if already inserted.
-------------|-----------------|------------------|
patitentID | Patient Name | Contact no |
-------------|-----------------|------------------|
4 | David | 01245785874 |
table:patient
My SQL is: (it does not work)
INSERT INTO `queue`(`patientID`, `Visiting_date`)
SELECT patient.`patientID`,’CURDATE()’ FROM `patient`
WHERE NOT EXISTS (
SELECT `patientID`, `visiting_date`FROM `queue`
WHERE `patientID` = '4' AND `visting_date`=CURDATE()
) LIMIT 1;
You could set a foreign key to make sure the patients id exists.
In the Queue table you can set patientID as unique, this makes sure you can insert only unique id's in the queue table.
Also if you would like to be able to insert the same userID but with different dates you could specify unique constraint for multiple columns in MySQL.
If you want to solve it with a mysql query only you can use this question.
I would use a separate query to check if there is a user with that ID in that table.
SELECT * FROM queue WHERE PatientID = 4;
and then check the result of that query, if it returns a row, that means that there is a user in there and you don't do anything.
If the query doesn't return a row, that means you can now use a query to inert a user. Like this
INSERT INTO queue (PatientID, VisitingDate);

Select MySQL records that conflict with a proposed unique index

I have a set of records that I want to add a unique index to, however some existing records conflict with that index, so I want to identify them and remove them in order that the constraint can be placed on the data.
Is there a way I can write a SELECT query based around any record that contradicts the unique index?
Example:
Table has columns
id | user | question_id | response | is_current
I want a unique index such that
user | question_id | response |is_current
is not duplicated.
Is it possible to SELECT all records where that set of values is not unique?
Show non-unique:
select user,question_id,response,is_current,count(*) as theCount
from tablename
group by user,question_id,response,is_current
having theCount>1

INSERT query for unique records-Mysql

I have a table like this
id | name | zip
1 | abc | 1234
2 | xyz | 4321
3 | asd | 1234
I want to insert records such that the id and name when inserted may have the same value but if the value of zip is also same for that particular record it is not inserted. If not it should be inserted.
eg: I can insert another row with value for id=1 and value for name= abc but if that record also has zip=1234 it should not be inserted.
How can I achieve this.
Create two unique indexes:
create unique index idx_table_name_zip on table(name, zip)
create unique index idx_table_id_zip on table(id, zip)
The database will then guarantee the uniqueness you want to enforce.
Make a Primary Key from id, name and zip combined
ALTER TABLE table ADD PRIMARY KEY(id, name, zip)
With this a row/record is marked duplicate if all the three columns are same otherwise it is a perfectly fine non-duplicate record.
check this for more here
you need to make a check before inserting the row, for exmpale
select * from table where zip = #zip and name = #name and id = #id
if no rows return you can do the insert...

How to select distinct value from one column only

I have records as follows:
key | name
--------------
1111 | aa
1111 | bb
2222 | cc
I need to select the key and name when the key value is distinct. When I tried:
select distinct key, name from table;
I got all the rows since the query takes distinct for the combination of the columns: key and name. But, what I need is only distinct key and I don't care about the name. I have a lot of records, so I need a practical method.
Query:
SELECT `key`, MAX(`name`) as name
FROM `table`
GROUP BY `key`
Why not just:
SELECT distinct key
FROM table
or
SELECT key, name
FROM table
GROUP BY key
SELECT key, name FROM table GROUP BY key;
This returns one row for each distinct value of key, and the value of name is arbitrarily chosen from the rows in that group. In practice, MySQL tends to return the value of name from the row physically stored first in the group, but that's not guaranteed.
As other answers show, you can put name into an aggregate expression.
How about this:
select * from table group by key having count(key) = 1
If you do not care about not groupped fields try this query -
select key, name from table group by key order by name
MySQL lets selecting fields without using aggregate function.
order by name helps to select first name from the group.