0

首先是一些数据库切割:

+-----+----------------------------------------+----------+--------+
| id  | name                                   | code     | parent |
+-----+----------------------------------------+----------+--------+
|   1 | Basic Materials                        |      101 |   NULL |
|   2 | Consumer Cyclical                      |      102 |   NULL |
|   3 | Financial Services                     |      103 |   NULL |
|   4 | Real Estate                            |      104 |   NULL |
|   5 | Consumer Defensive                     |      205 |   NULL |
|   6 | Healthcare                             |      206 |   NULL |
|   7 | Utilities                              |      207 |   NULL |
|   8 | Communication Services                 |      308 |   NULL |
|   9 | Energy                                 |      309 |   NULL |
|  10 | Industrials                            |      310 |   NULL |
|  11 | Technology                             |      311 |   NULL |
|  12 | Agriculture                            |    10101 |    101 |
|  13 | Agricultural Inputs                    | 10101001 |  10101 |
|  14 | Building Materials                     |    10102 |    101 |
|  15 | Building Materials                     | 10102002 |  10102 |
|  16 | Chemicals                              |    10103 |    101 |
|  17 | Chemicals                              | 10103003 |  10103 |
|  18 | Specialty Chemicals                    | 10103004 |  10103 |
|  19 | Coal                                   |    10104 |    101 |
|  20 | Forest Products                        |    10105 |    101 |
|  21 | Lumber & Wood Production               | 10105006 |  10105 |
|  22 | Paper & Paper Products                 | 10105007 |  10105 |
|  23 | Metals & Mining                        |    10106 |    101 |
|  24 | Aluminum                               | 10106008 |  10106 |
|  25 | Copper                                 | 10106009 |  10106 |
|  26 | Gold                                   | 10106010 |  10106 |
|  27 | Industrial Metals & Minerals           | 10106011 |  10106 |
|  28 | Silver                                 | 10106012 |  10106 |
|  29 | Steel                                  |    10107 |    101 |
|  30 | Coal                                   | 10104005 |  10104 |

所以现在在父列中必须是 id 列值,其中父 = 代码。我正在尝试这样做,但我自己无法解决这个问题。

例如:

在父列中 id = 12 的行中应该有 value = 1 因为在代码列中存在与父列中相同的值。

感谢帮助!

4

2 回答 2

0
update table as a 
left join table as b 
on a.parent=b.code 
set a.parent=b.id
于 2013-09-16T12:41:04.710 回答
0

您可以使用多表UPDATE语法进行自联接:

UPDATE my_table a JOIN my_table b ON b.code = a.parent SET a.parent = b.id;

然后,您可能希望在更改后的表上定义外键约束:

ALTER TABLE my_table ADD FOREIGN KEY (parent) REFERENCES my_table (id);

sqlfiddle上查看。

但是,您应该记住 MySQL 不支持递归函数,因此不太适合这种表示分层数据的邻接列表模型:您可能希望考虑使用嵌套集或传递闭包模型。

于 2013-09-16T12:42:02.110 回答