Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert using select distinct

Let's say, I have 2 tables t1 and t2.

create table t1 
{
id int not null,
col1 int null,
col2 int null,
col3 int null
}

create table t2
{
id uniqueidentifier not null,
col1 int null,
col2 int null,
col3 int null
}

I want to insert the below resultset into table t2.

select distinct col1, col2, col3 from t1

How can I achieve this using a query? I tried below statement but I know it's syntactically wrong.

insert into t2
select newid(), distinct col1, col2, col3 from t1
like image 1000
stech Avatar asked Jan 09 '13 13:01

stech


People also ask

Can we use distinct in SELECT query?

The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

How do I insert without duplicates in SQL?

Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.

How does SELECT distinct work?

The DISTINCT keyword in the SELECT clause is used to eliminate duplicate rows and display a unique list of values. In other words, the DISTINCT keyword retrieves unique values from a table.

How do I add distinct?

The distinct keyword is used with select keyword in conjunction. It is helpful when we avoid duplicate values present in the specific columns/tables. The unique values are fetched when we use the distinct keyword. SELECT DISTINCT returns only distinct (different) values.


2 Answers

insert into t2
select newid(),a.*
from
(Select distinct col1, col2, col3 from t1) a
like image 134
bummi Avatar answered Sep 19 '22 18:09

bummi


You can omit uniqueidentifier field if it's auto generated.

INSERT INTO t2 (col1, col2, col3)
SELECT DISTINCT col1, col2, col3 FROM t1

More on that Using uniqueidentifier Data

like image 35
peterm Avatar answered Sep 19 '22 18:09

peterm