如何使用INSERT INTO多次选择插入?

时间:2013-10-04 13:53:50

标签: mysql sql

我试图为表中的每个字段插入两个数据,如下所示:

INSERT INTO `wp_postmeta` (post_id, meta_key, meta_value)
SELECT post_id, 'custom', custom
SELECT post_id, '_custom', 'field_514e91e73640d'
FROM `wp_temp`
WHERE custom IS NOT NULL

然而,这不起作用。无论如何在MySQL的一个查询中实现这一点?感谢。

3 个答案:

答案 0 :(得分:6)

INSERT INTO `wp_postmeta` (post_id, meta_key, meta_value)
SELECT post_id, 'custom', custom FROM `wp_temp` WHERE custom IS NOT NULL
UNION ALL
SELECT post_id, '_custom', 'field_514e91e73640d' FROM `wp_temp` WHERE custom IS NOT NULL

答案 1 :(得分:1)

每个FROM都需要单独的WHERESELECT子句,但UNION或UNION ALL可以使用。{/ p>

INSERT INTO `wp_postmeta` (post_id, meta_key, meta_value)
SELECT post_id, 'custom', custom
FROM `wp_temp`
WHERE custom IS NOT NULL
UNION 
SELECT post_id, '_custom', 'field_514e91e73640d'
FROM `wp_temp`
WHERE custom IS NOT NULL

答案 2 :(得分:0)

UNION ALL

INSERT INTO `wp_postmeta` (post_id, meta_key, meta_value)
SELECT post_id, '_custom', 'field_514e91e73640d'
FROM `wp_temp`
WHERE custom IS NOT NULL

UNION ALL

SELECT post_id, 'custom', custom
FROM `wp_temp`
WHERE custom IS NOT NULL