Reputation: 5566
In MySQL
I have a table named tasks and I want to select two columns (keyid and proyect). These pairs might repeat so I just want to select one of each combination.
Then I want to insert the result into the columns user and proyect of a second table.
Can anyone provide the syntax to accomplish this?
Upvotes: 0
Views: 35
Reputation: 23
It's called an INSERT SELECT
.
INSERT INTO table2 (user, proyect) SELECT keyid, proyect FROM tasks LIMIT 1
Make sure you list the columns in order on the same order in the INSERT
and the SELECT
.
The LIMIT 1
will just return one record. You could add a WHERE
on the SELECT
or remove/change the limit to fit your needs.
Upvotes: 1
Reputation: 13110
I'm not entirely sure what you mean by one of each but I'm guessing you want something like:
INSERT
INTO table2 (keyid,proyect)
SELECT DISTINCT keyid, proyect
FROM table1
Or
INSERT
INTO table2 (keyid,proyect)
SELECT keyid, proyect
FROM table1
GROUP BY keyid, proyect
Personally I prefer DISTINCT
in this case, as this is how you have phrased the question.. I tend to use GROUP BY
only when necessary or when trying to conceptually create groups.
This is very easy to find online; INSERT ... SELECT Syntax
Upvotes: 2
Reputation: 333
You didn't indicate how you would filter the source data. You would need to add a WHERE clause at the end of the SELECT to help limit the data.
INSERT INTO SecondTable (`keyid`, `proyect`)
SELECT `keyid`, `proyect` FROM `tasks` LIMIT 1
Upvotes: 1