the title is not really helpful. Sorry. I better explain with code. I need a query in MySQL for the following problem:
Build schema:
CREATE TABLE AsIs
(
`PN` VARCHAR(10),
`Origin`VARCHAR(10),
`Sub`VARCHAR(10)
);
INSERT INTO AsIs
VALUES ('11111', 'List1', '22222'), ('98765', 'List2', '123456');
I create a table with the column subs:
CREATE TEMPORARY TABLE `Subs` SELECT `sub` AS `PN` FROM AsIs;
I create a table to union the values from table AsIs and table subs
:
CREATE TEMPORARY TABLE `UnionAsISwithSubs`
SELECT `PN` FROM AsIs UNION SELECT `PN` FROM `subs`;
And finally I create the last table to add the information from the AsIs table:
`CREATE TABLE `FinalList`
SELECT `UnionAsISwithSubs`.`PN`,`AsIs`.`Origin`,`AsIs`.`sub`
FROM `UnionAsISwithSubs`
LEFT JOIN AsIs ON `UnionAsISwithSubs`.`PN` = `AsIs`.`PN;
There are for sure better ways to do this, but my main question is, how can i update the column 'Origin` with the values from the row above. So it should like this:
CREATE TABLE ShouldBe Like AsIs;
INSERT INTO ShouldBe
VALUES('11111', 'List1', '22222'),('98765', 'List2', '123456'),
('22222', 'List1', ''),('123456', 'List2', '');
Many thanks in advance for your help.
I have simulate it with SQL fiddle. Please follow the link: