如何根据不同记录的存在来插入/更新可能存在的关系记录

时间:2015-02-18 13:42:35

标签: mysql database insert sql-update

A有一个关系表,它将标签与照片联系起来:

table: tag_photo_x
photo_id
tag_id
status

PRIMARY INDEX: photo_id,tag_id

我正在将一些标签合并在一起,因为它们非常相似(即:风景,风景)。因此,照片可能已经或可能没有两个标签的记录。

在这个例子中,我想使用1个查询来浏览标签“landscapes”的所有关系,并插入“landscape”的记录。

我的问题是我无法理解如何编写单个查询,该查询将根据“风景”记录和“重复键”的存在插入“风景”记录,更新状态= 1

我会有相当多的照片和标签,因此需要尝试在单个查询中执行此操作。

1 个答案:

答案 0 :(得分:0)

如果您想landscape插入landscape,请执行insert

insert into tag_photo_x(photo_id, tag_id)
    select photo_id, 'landscape'
    from tag_photo_x tp
    where tag_id = 'landscapes' and
          not exists (select 1
                      from tag_photo_x tp2
                      where tp.photo_id = tp2.photo_id and
                            tp2.tag_id = 'landscape'
                     );

如果愿意,您可以删除landscapes标记。