Achelon
Achelon

Reputation: 37

SELECT on INSERT's VALUES

my question is if there is any way to do this:

INSERT INTO t1 (c1, c2, c3, c4, c5)
VALUES (SELECT c1 FROM t2, 15, 2, 'Name', SELECT c5 FROM t4);

I know I have the INSERT INTO t1 FROM SELECT, but I can't use it for this special case, and I wanted to know if it would be possible to add selects in the insert values.

Upvotes: 0

Views: 69

Answers (5)

Mostafa Darwish
Mostafa Darwish

Reputation: 91

you should use somthing like this:

INSERT INTO  t1 (c1, c2, c3, c4, c5)
SELECT
   f1.c1, 15, 2, 'Name', f2.c5
FROM
   (SELECT c1 FROM t2) AS f1
    CROSS JOIN
   (SELECT c5 FROM t4) AS f2

Upvotes: 0

Yes, there is way to make It. You need to use parenthesis for each SELECT.

INSERT INTO t1 (c1, c2, c3, c4, c5)
VALUES ((SELECT c1 FROM t2), 15, 2, 'Name', (SELECT c5 FROM t4));

Remember that your select should return only 1 value.

Upvotes: 0

happybacon
happybacon

Reputation: 84

This should work for you.

INSERT INTO `pages` (name, content, modified) 
VALUES ('new page', (SELECT `description` FROM `categories` WHERE id = '4'), NOW());

I think you just forgot to put the sub-query in parentheses.

Upvotes: 0

parakmiakos
parakmiakos

Reputation: 3020

Yes it is possible, but not in the syntax you mention:

INSERT INTO t1 (c1, c2, c3, c4, c5)
SELECT t2.c1 , 15, 2, 'Name', t4.c5
FROM t2, t4
WHERE t2.some_field = t4.some_other_field

The t2 and t4 tables should have some logical join between them or a WHERE condition of their own.

Upvotes: 0

Jaykumar Patel
Jaykumar Patel

Reputation: 27614

Sub query use with parenthesis use right there like:

INSERT INTO t1 (c1, c2, c3, c4, c5)
VALUES ((SELECT c1 FROM t2), 15, 2, 'Name', (SELECT c5 FROM t4));

Upvotes: 1

Related Questions