【问题标题】:Only insert when exists (with the same ID)仅在存在时插入(具有相同的 ID)
【发布时间】:2015-10-23 17:30:51
【问题描述】:

我有一个包含这些字段的表格:

meta_id | post_id | meta_key | meta_value

这实际上是一个 WordPress postmeta 表。

一些帖子有一个 postmeta 条目,其中 meta_key 是 _price。我需要的是遍历表,并插入另一行,meta_key = _regular_price,相同的 post_id 和相同的 meta_value。

所以我检查是否存在具有该 meta_key 的 postmeta 条目,并添加另一个具有不同 meta_key 的条目。听起来很简单,但我该如何实现呢?

【问题讨论】:

    标签: mysql


    【解决方案1】:

    此查询将为所有 meta_key = '_price' 的帖子插入具有现有 post_id 和 meta_key 值 '_regular_price' 的新行。 meta_id 和 meta_value 列将为 null 或其默认值(如果有任何默认约束)。

    insert postmeta (post_id, meta_key)
    select post_id, '_regular_price' from postmeta p1
    where exists (select 1 from postmeta where meta_key = '_price' and p1.post_id = post_id)
    

    如果您打算多次运行它,您可能需要添加一个条件来检查是否存在“_regular_price”元密钥:

    and not exists (select 1 from postmeta where meta_key = '_regular_price' and p1.post_id = post_id)
    

    Sample SQL Fiddle

    【讨论】:

    • 这可能可行...如何将 meta_value 设置为相同的值?
    • 只需要在插入的列中添加并选择:insert postmeta (meta_id, post_id, meta_key) select meta_id, post_id, '_regular_price' from
    • 也就是说,如果 meta_id 不是自动递增的。我不知道postmeta 表是什么样子的。
    • 我还必须添加一个额外的where 声明,但总的来说,你给了我一个正确的方向。感谢那。 (sqlfiddle.com/#!9/0bef6)
    • @Uhehesh 啊,是的,如果同一个 post_id 有任何其他 meta_key,你会得到重复的行;我没想到。
    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-02
    • 1970-01-01
    相关资源
    最近更新 更多