如何在 inner joined table 为空的地方插入记录?

How to insert record where inner joined table is null?

我有一个主 table,其中包含几个 Wordpress post 类型,例如:

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

post 和 post_type 作为 zoacres-property 包含位于 wp_postmeta table:

中的特定元值
meta_id | post_id | meta_key | meta_value
  100       2         price       5000

如您所见,ID 为 1 的 post 没有元键 price

有什么方法可以在缺少的 post 中添加带有 pricemeta_key 吗?

您可以使用 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 是 auto-generated 列,那么您可以将其从查询中删除:

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'
    )

您可以使用带有插入的左连接

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