我知道在从数据库中选择行后,我可以使用子查询进行插入。
INSERT INTO wp_43_term_relationships (object_id, term_taxonomy_id, term_order)
SELECT ID, 8363, 0 FROM
( SELECT DISTINCT
wp_43_posts.ID
FROM
wp_43_posts
INNER JOIN wp_43_term_relationships ON wp_43_term_relationships.object_id = wp_43_posts.ID
INNER JOIN wp_43_term_taxonomy ON wp_43_term_taxonomy.term_taxonomy_id = wp_43_term_relationships.term_taxonomy_id
WHERE (wp_43_term_taxonomy.term_id = 4613 OR wp_43_term_taxonomy.term_id = 4615) AND wp_43_term_taxonomy.term_id != 8363 ) posts
但是,如果我不需要硬编码8363,而是需要从另一个查询中获取它呢?例如,我需要从
派生它SELECT
wp_43_term_taxonomy.term_taxonomy_id
FROM
wp_43_term_taxonomy
WHERE
wp_43_term_taxonomy.term_id = 8363
答案 0 :(得分:1)
将它带入子查询并使用额外的连接:
INSERT INTO wp_43_term_relationships (object_id, term_taxonomy_id, term_order)
SELECT ID, someval, 0 FROM
( SELECT DISTINCT
wp_43_posts.ID,t.term_taxonomy_id someval
FROM
wp_43_posts
INNER JOIN wp_43_term_relationships ON wp_43_term_relationships.object_id = wp_43_posts.ID
INNER JOIN wp_43_term_taxonomy ON wp_43_term_taxonomy.term_taxonomy_id = wp_43_term_relationships.term_taxonomy_id
WHERE (wp_43_term_taxonomy.term_id = 4613 OR wp_43_term_taxonomy.term_id = 4615) AND wp_43_term_taxonomy.term_id != 8363
join wp_43_term_taxonomy t on t.term_id = 8363 ) posts
答案 1 :(得分:1)
是的,您可以,请参阅下面的修改后的查询。基本上将该列包含在要为INSERT
语句创建的子查询select子句中。此外,您当然不需要该条件AND wp_43_term_taxonomy.term_id != 8363
INSERT INTO wp_43_term_relationships (object_id, term_taxonomy_id, term_order)
SELECT ID, term_id, 0
FROM
(SELECT DISTINCT
wp_43_posts.ID,
wp_43_term_taxonomy.term_id
FROM wp_43_posts
INNER JOIN wp_43_term_relationships
ON wp_43_term_relationships.object_id = wp_43_posts.ID
INNER JOIN wp_43_term_taxonomy
ON wp_43_term_taxonomy.term_taxonomy_id = wp_43_term_relationships.term_taxonomy_id
WHERE wp_43_term_taxonomy.term_id IN(4613, 4615) posts
答案 2 :(得分:1)
如果用()中的第二个查询替换常量,它应该可以工作。 像这样:
INSERT INTO wp_43_term_relationships (object_id, term_taxonomy_id,term_order)
SELECT ID,
(SELECT wp_43_term_taxonomy.term_taxonomy_id FROM wp_43_term_taxonomy WHERE wp_43_term_taxonomy.term_id = 8363),
0 FROM
... remaining of the original ...
至少如果你只需要1个值,否则最好将这个额外的表加入其他表。