I've done this before, but I don't remember how. I need to select all rows with unique values from several columns in one table, and insert them into one column in a different table. For the destination table they need to be on separate rows in the destination column.
Here's an example:
Source Table
+-----+------------+------------+------------+------------+
| id | column1 | column2 | column3 | column4 |
+-----+------------+------------+------------+------------+
| 1 | value1 | value1 | value1 | value1 |
+-----+------------+------------+------------+------------+
| 2 | value2 | value3 | value4 | value5 |
+-----+------------+------------+------------+------------+
Destination Table
+-----+-----------+
| id | column1 |
+-----+-----------+
| 1 | value1 |
+-----+-----------+
| 2 | value2 |
+-----+-----------+
| 3 | value3 |
+-----+-----------+
| 4 | value4 |
+-----+-----------+
| 5 | value5 |
+-----+-----------+
I tried this query but of course it didn't work because the columns aren't equal.
INSERT INTO table2 (column1)
SELECT DISTINCT column1, column2, column3, column4
FROM table1
EternalHourEternalHour
asked Feb 26, 2015 at 11:39
2 Answers 2
Try with union
insert into table2(column1)
select column1 from table1
union
select column2 from table1
union
select column3 from table1
answered Feb 26, 2015 at 13:39
Try this...
SELECT col1,
col2
FROM
(SELECT rownum X,col_table1 FROM table1
) T1
INNER JOIN
(SELECT rownum Y, col_table2 FROM table2
) T2
ON T1.X=T2.Y;
Erik
4,8434 gold badges29 silver badges58 bronze badges
-
Do you have any sample data with output from this query ???RolandoMySQLDBA– RolandoMySQLDBA2015年08月20日 16:26:34 +00:00Commented Aug 20, 2015 at 16:26
-
2This probably solves some problem but not the one in this question.Andriy M– Andriy M2015年08月20日 16:26:40 +00:00Commented Aug 20, 2015 at 16:26
-
How does this do the insert ?Rohit Gupta– Rohit Gupta2016年02月02日 03:28:42 +00:00Commented Feb 2, 2016 at 3:28
lang-sql
UNPIVOT
which is what you are thinking of.