【问题标题】:How to insert record where inner joined table is null?如何插入内部联接表为空的记录?
【发布时间】:2020-08-25 08:04:18
【问题描述】:

我有一个主表,其中包含几种 Wordpress 帖子类型,例如:

ID | post_title | post_type
 1      foo         zoacres-property
 2      foo2        zoacres-property
 3      foo3        post

post_type 作为zoacres-property 的帖子包含位于wp_postmeta 表中的特定元值:

meta_id | post_id | meta_key | meta_value
  100       2         price       5000

您可以看到 ID 为 1 的帖子没有元键 price

有没有办法在缺少的帖子中将meta_keyprice 添加到0?

【问题讨论】:

    标签: mysql sql subquery sql-insert


    【解决方案1】:

    你可以使用not exists:

    insert into wp_postmeta (meta_id, post_id, meta_key, meta_value)
    select 100, p.id, 'price', 0
    from mytable t
    where
        t.post_type = 'zoacres-property'
        and not exists (
            select 1
            from wp_postmeta w
            where w.post_id = t.id and w.meta_key = 'price'
        )
    

    如果meta_id 是自动生成的列,那么您可以将其从查询中删除:

    insert into wp_postmeta (post_id, meta_key, meta_value)
    select p.id, 'price', 0
    from mytable t
    where
        t.post_type = 'zoacres-property'
        and not exists (
            select 1
            from wp_postmeta w
            where w.post_id = t.id and w.meta_key = 'price'
        )
    

    【讨论】:

      【解决方案2】:

      您可以将左连接与插入一起使用

      insert into meta (`post_id`, `meta_key`, `meta_value`)
      select p.ID, 'price', 0
      from post p
      left join meta m on p.ID = m.post_id and m.meta_key = 'price'
      where p.post_type = 'zoacres-property'
            and m.post_id is null
      

      DEMO

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-29
        • 2014-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多