编辑 2
这是一个修改后的选择查询,它根据词条是否在标题中来匹配词条和帖子:
select p.id, tt.term_taxonomy_id, t.term_id, t.name, p.post_title
from wp_terms t
join wp_posts p on INSTR(p.post_title, t.name)
join wp_term_taxonomy tt on tt.term_id = t.term_id
where p.post_type = 'post'
这是您要使用的插入查询(请注意,如果由于主键约束而插入重复的 object_id 和 term_taxonomy_id 对,此查询将引发错误):
insert into wp_term_relationships (object_id, term_taxonomy_id, term_order)
select p.id, tt.term_taxonomy_id, 0
from wp_terms t
join wp_posts p on INSTR(p.post_title, t.name)
join wp_term_taxonomy tt on tt.term_id = t.term_id
where p.post_type = 'post'
如果确实遇到主键约束错误,可以使用insert ignore
insert ignore into wp_term_relationships (object_id, term_taxonomy_id, term_order)
select p.id, tt.term_taxonomy_id, 0
from wp_terms t
join wp_posts p on INSTR(p.post_title, t.name)
join wp_term_taxonomy tt on tt.term_id = t.term_id
where p.post_type = 'post'
编辑 1:
这是一个可能对您有用的查询:
insert into wp_term_relationships (object_id, term_taxonomy_id, term_order)
select p.id, tt.term_taxonomy_id, 0
from wp_posts p
join wp_terms t on t.name = substring_index(p.post_title, ' ', 1)
join wp_term_taxonomy tt on tt.term_id = t.term_id
where p.post_type = 'post'
在这里,我假设标题与您的示例类似。您可能需要调整分隔符。
此外,我会自行运行选择查询来测试您要返回的数据,并确保您没有收到重复数据和其他数据。是的,一定要先备份你的数据库。
select p.id, tt.term_taxonomy_id, 0
from wp_posts p
join wp_terms t on t.name = substring_index(p.post_title, ' ', 1)
join wp_term_taxonomy tt on tt.term_id = t.term_id
where p.post_type = 'post'
这里还有一个更好的调试结果选择查询:
select p.id, tt.term_taxonomy_id, t.term_id, substring_index(p.post_title, ' ', 1)
from wp_posts p
join wp_terms t on t.name = substring_index(p.post_title, ' ', 1)
join wp_term_taxonomy tt on tt.term_id = t.term_id
where p.post_type = 'post'