从部分重新创建完整的表

时间:2014-06-02 19:08:29

标签: mysql sql

我真的迷失了我已经有一段时间的问题。

我的表看起来像那样

object No value  
1      0  foo 1  
1      3  foo 2  
1      4  foo 3  
1      8  foo 4  
2      0  faa 1  
2      8  faa 2   

我希望能够重建表格,如:

object No value OldNo  
1      0  foo 1 0  
1      1  foo 1 0  
1      2  foo 1 0  
1      3  foo 2 3  
1      4  foo 3 3  
1      5  foo 3 3  
1      6  foo 3 3  
1      7  foo 3 3  
1      8  foo 4 4  
2      0  faa 1 1  
2      1  faa 1 1  
2      2  faa 1 1  
2      3  faa 1 1  
2      4  faa 1 1  
2      5  faa 1 1  
2      6  faa 1 1  
2      7  faa 1 1  
2      8  faa 2 2  

我的表格由一个程序填充,这意味着我总是可以强制程序为每一行输入数据,但我认为只有在需要时插入行才会更简洁。

我的问题: - 有人知道如何从表1创建视图2吗? - 在处理成本方面,我的做事方式是更好还是更差?

感谢您的帮助。

巴特

1 个答案:

答案 0 :(得分:0)

我不确定我会效仿。你的意思是这样的...... ??

SELECT DISTINCT 1 0 foo 1

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(obj INT NOT NULL
,seq INT NOT NULL
,val VARCHAR(12) NOT NULL
,PRIMARY KEY(obj,seq)
);

INSERT INTO my_table
VALUES
(1 ,0 ,'foo 1'), 
(1 ,3 ,'foo 2'),
(1 ,4 ,'foo 3'),
(1 ,8 ,'foo 4'),
(2 ,0 ,'faa 1'),
(2 ,8 ,'faa 2'); 

CREATE TABLE ints(i INT NOT NULL PRIMARY KEY);

INSERT INTO ints VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);

SELECT obj
     , i
     , val
     , seq 
  FROM 
     ( SELECT * 
         FROM ints 
        WHERE i BETWEEN 0 AND 8
     ) a 
     , my_table 
 ORDER 
    BY obj,seq,i;
+-----+---+-------+-----+
| obj | i | val   | seq |
+-----+---+-------+-----+
|   1 | 0 | foo 1 |   0 |
|   1 | 1 | foo 1 |   0 |
|   1 | 2 | foo 1 |   0 |
|   1 | 3 | foo 1 |   0 |
|   1 | 4 | foo 1 |   0 |
|   1 | 5 | foo 1 |   0 |
|   1 | 6 | foo 1 |   0 |
|   1 | 7 | foo 1 |   0 |
|   1 | 8 | foo 1 |   0 |
|   1 | 0 | foo 2 |   3 |
|   1 | 1 | foo 2 |   3 |
|   1 | 2 | foo 2 |   3 |
|   1 | 3 | foo 2 |   3 |
|   1 | 4 | foo 2 |   3 |
|   1 | 5 | foo 2 |   3 |
|   1 | 6 | foo 2 |   3 |
|   1 | 7 | foo 2 |   3 |
|   1 | 8 | foo 2 |   3 |
|   1 | 0 | foo 3 |   4 |
|   1 | 1 | foo 3 |   4 |
|   1 | 2 | foo 3 |   4 |
|   1 | 3 | foo 3 |   4 |
|   1 | 4 | foo 3 |   4 |
|   1 | 5 | foo 3 |   4 |
|   1 | 6 | foo 3 |   4 |
|   1 | 7 | foo 3 |   4 |
|   1 | 8 | foo 3 |   4 |
|   1 | 0 | foo 4 |   8 |
|   1 | 1 | foo 4 |   8 |
|   1 | 2 | foo 4 |   8 |
|   1 | 3 | foo 4 |   8 |
|   1 | 4 | foo 4 |   8 |
|   1 | 5 | foo 4 |   8 |
|   1 | 6 | foo 4 |   8 |
|   1 | 7 | foo 4 |   8 |
|   1 | 8 | foo 4 |   8 |
|   2 | 0 | faa 1 |   0 |
|   2 | 1 | faa 1 |   0 |
|   2 | 2 | faa 1 |   0 |
|   2 | 3 | faa 1 |   0 |
|   2 | 4 | faa 1 |   0 |
|   2 | 5 | faa 1 |   0 |
|   2 | 6 | faa 1 |   0 |
|   2 | 7 | faa 1 |   0 |
|   2 | 8 | faa 1 |   0 |
|   2 | 0 | faa 2 |   8 |
|   2 | 1 | faa 2 |   8 |
|   2 | 2 | faa 2 |   8 |
|   2 | 3 | faa 2 |   8 |
|   2 | 4 | faa 2 |   8 |
|   2 | 5 | faa 2 |   8 |
|   2 | 6 | faa 2 |   8 |
|   2 | 7 | faa 2 |   8 |
|   2 | 8 | faa 2 |   8 |
+-----+---+-------+-----+
54 rows in set (0.00 sec)