问题描述
我有一个主表,其中包含几种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_key
和price
设置为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