我已经在MySQL以下结构,表 'images_tags':MySQL查询的重新分配中的图片标签和避免重复
id | image_id | tag_id
----------------------
1 | 243 | 52
2 | 94 | 52
3 | 56 | 52
4 | 56 | 53
5 | 56 | 54
表 '标签':
id | tag
---------------
52 | fashion
53 | cars
54 | sports
55 | bikes
我建立一个在我的CMS中删除一个标签,因为我需要将包含该标签的所有图片重新分配给另一个标签。问题是图片已经可以分配新的标签,我想避免可能的重复记录。
我无法找到正确的方式做直SQL所以我在PHP尝试如下:
$result=mysql_query("select image_id from images_tags where tag_id='".$oldtag."'");
while($row=mysql_fetch_assoc($result)){
$result2=mysql_query("select id from images_tags
where image_id='".$row['image_id']."' and tag_id='".$newtag."'");
if(mysql_num_rows($result2)==0){
mysql_query("update images_tags set tag_id='".$newtag."'
where image_id='".$row['image_id']."' and tag_id='".$newtag."'");
}
}
正如你看到的,我的代码是非常糟糕的和非有效,因为我跑在迭代中查询。你知道更好的方法来做到这一点吗?最好只在一个SQL查询中。谢谢。
你应该在'image_id'和'tag_id'上有一个复合唯一键。 – ceejayoz
'$ row ['id']'应该是'$ row ['image_id']'? '$ newtag'从哪里来? – Barmar
抱歉写错问题。固定。 –