mysql,插入select子查询

时间:2012-05-03 09:43:33

标签: mysql

我在product_category表中有很多产品,category_id为5。 我添加了一个新的category_id 19。 如何将类别5中的所有产品添加到类别19中?

我正在尝试做这样的事情:

insert into product_categories( category_id, product_id )
select 19,
   (select product_id
    from product_categories
    where category_id = 5)

但我收到sub query returns more than 1 row错误。

4 个答案:

答案 0 :(得分:10)

试试这个:

INSERT INTO product_categories (category_id, product_id)
  SELECT 19 AS category_id, product_id 
  FROM product_categories 
  WHERE category_id =5;

答案 1 :(得分:2)

尝试这样的事情:

INSERT INTO product_categories( category_id, product_id )
SELECT 19, product_id FROM product_categories WHERE category_id =5

答案 2 :(得分:2)

你可以这样做:

INSERT INTO table_a (field, field, timestamp) 
 VALUES (
     (SELECT id FROM tablex WHERE id = :xid LIMIT 1),
     (SELECT id FROM tabley WHERE id = :yid LIMIT 1),
     NOW()
 )

答案 3 :(得分:0)

尝试使用限制

INSERT INTO product_categories( category_id, product_id ) SELECT 19 , (

SELECT product_id FROM product_categories WHERE category_id =5 LIMIT 1)