2

我有一个旧数据库,其中包含大量记录(或多或少),其中有一个标签列(标签以竖线分隔),如下所示:

    Breakfast
    Breakfast|Brunch|Buffet|Burger|Cakes|Crepes|Deli|Dessert|Dim Sum|Fast Food|Fine Wine|Spirits|Kebab|Noodles|Organic|Pizza|Salad|Seafood|Steakhouse|Sushi|Tapas|Vegetarian
    Breakfast|Brunch|Buffet|Burger|Deli|Dessert|Fast Food|Fine Wine|Spirits|Noodles|Pizza|Salad|Seafood|Steakhouse|Vegetarian
    Breakfast|Brunch|Buffet|Cakes|Crepes|Dessert|Fine Wine|Spirits|Salad|Seafood|Steakhouse|Tapas|Teahouse
    Breakfast|Brunch|Burger|Crepes|Salad
    Breakfast|Brunch|Cakes|Dessert|Dim Sum|Noodles|Pizza|Salad|Seafood|Steakhouse|Vegetarian
    Breakfast|Brunch|Cakes|Dessert|Dim Sum|Noodles|Pizza|Salad|Seafood|Vegetarian
    Breakfast|Brunch|Deli|Dessert|Organic|Salad
    Breakfast|Brunch|Dessert|Dim Sum|Hot Pot|Seafood
    Breakfast|Brunch|Dessert|Dim Sum|Seafood
    Breakfast|Brunch|Dessert|Fine Wine|Spirits|Noodles|Pizza|Salad|Seafood
    Breakfast|Brunch|Dessert|Fine Wine|Spirits|Salad|Vegetarian

有没有一种方法可以检索每个标签并将其插入到 tag_id | tag_nm仅使用 MySQL 的新表中?

4

2 回答 2

2

这是我使用 PHP 的尝试......,我想这可以通过一个聪明的 MySQL 查询更有效。我也把它的关系部分放在那里。没有转义和错误检查。

$rs = mysql_query('SELECT `venue_id`, `tag` FROM `venue` AS a');
while ($row = mysql_fetch_array($rs)) {
    $tag_array = explode('|',$row['tag']);
    $venueid = $row['venue_id'];
    foreach ($tag_array as $tag) {
        $rs2 = mysql_query("SELECT `tag_id` FROM `tag` WHERE tag_nm = '$tag'");
        $tagid = 0;
        while ($row2 = mysql_fetch_array($rs2)) $tagid = $row2['tag_id'];
        if (!$tagid) {
            mysql_execute("INSERT INTO `tag` (`tag_nm`) VALUES ('$tag')");
            $tagid = mysql_insert_id;
        }
        mysql_execute("INSERT INTO `venue_tag_rel` (`venue_id`, `tag_id`) VALUES ($venueid, $tagid)");
    }
}
于 2010-11-17T05:49:57.770 回答
1

在发现没有正式的拆分功能后,我只使用 MySQL 解决了这个问题,如下所示:

1:我创建了函数 strSplit

CREATE FUNCTION strSplit(x varchar(21845), delim varchar(255), pos int) returns varchar(255)
return replace(
replace(
substring_index(x, delim, pos),
substring_index(x, delim, pos - 1),
''
),
delim,
''
);

其次,我将新标签插入到我的新表中(真实姓名和列已更改,以保持简单)

INSERT IGNORE INTO tag (SELECT null, strSplit(`Tag`,'|',1) AS T FROM `old_venue` GROUP BY T)

冲洗并重复每列将 pos 增加一个(在这种情况下,我最多有 8 个分隔符)

三、搞定关系

INSERT INTO `venue_tag_rel` 
(Select a.`venue_id`, b.`tag_id` from `old_venue` a, `tag` b 
     WHERE 
     (         
     a.`Tag` LIKE CONCAT('%|',b.`tag_nm`) 
     OR a.`Tag` LIKE CONCAT(b.`tag_nm`,'|%') 
     OR a.`Tag` LIKE CONCAT(CONCAT('%|',b.`tag_nm`),'|%') 
     OR  a.`Tag` LIKE b.`tag_nm`
     ) 
)
于 2010-11-17T06:15:58.937 回答