如何在内部联接表为null的地方插入记录?

问题描述

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

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

post_typezoacres-property的帖子包含位于wp_postmeta表中的特定元值:

meta_id | post_id | meta_key | meta_value
  100       2         price       5000

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

在丢失的帖子中,是否有任何方法可以将meta_keyprice设置为0?

解决方法

您可以使用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_value)
select p.id,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,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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...