简体   繁体   中英

Inserting values from 1 table to another error

I'm Having 2 tables

modules_templates

and

templates

In table templates i have 75 records . I want to insert into table modules_templates some data which template_id in modules_templates = template_id from templates. I created this query :

INSERT INTO `modules_templates` (`module_template_id`,`module_template_modified`,`module_id`,`template_id`) VALUES  ('','2014-04-14 10:07:03','300',(SELECT template_id FROM templates WHERE 1))

And I'm having error that #1242 - Subquery returns more than 1 row , how to add all 75 rows in 1 query ?

Try this

INSERT 
    INTO `modules_templates` 
    (`module_template_id`,`module_template_modified`,`module_id`,`template_id`) 

    (SELECT '','2014-04-14 10:07:03','300',template_id FROM templates WHERE 1)

Your query didn't work because you were inserting value for one row, where last field ie result of sub query was multirow, so what you had to do was to put those single row values in sub-query so they are returned for each row in sub query.

Try this:

INSERT INTO `modules_templates`
(`module_template_id`,`module_template_modified`,`module_id`,`template_id`) 
SELECT '','2014-04-14 10:07:03','300',template_id FROM templates WHERE 1
INSERT INTO `modules_templates`
(`module_template_id`,`module_template_modified`,`module_id`,`template_id`) 
VALUES  
('','2014-04-14 10:07:03','300',
     (SELECT template_id FROM templates WHERE 1 limit 1))

To add more than one row, the field count/type must match :

INSERT INTO foo SELECT * FROM bar;

Please see the following link on how to do this properly :

http://www.w3schools.com/sql/sql_insert_into_select.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM