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
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.
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.
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.
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.
insert into t2
select newid(),a.*
from
(Select distinct col1, col2, col3 from t1) a
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With