0

I would like to insert data into table with one of the columns being populated by a select query. This is my SQL statement:

INSERT INTO books ( gid, type, membernumber,  changedate, user)
  VALUES( '2b4493e8-cae8-4624-8177-fcc96553c5be',
          2,
          (SELECT member FROM mem m JOIN group g ON m.uid = g.sgroup),
          TIMESTAMP '2017-01-03 00:00:00.000',
          'mark'
        );

What I want to achieve is for each insert, the membernumber will be taken from the mem table base on the JOIN it has with the group table.

When I execute this statement, I get the error:

More than one row returned by a subquery used as an expression

So for instance if the join will produce 20 rows then 20 records will be inserted with each member value replacing the membernumber in the insert for the 20 rows.

Update

I also have another query where two columns have to be replaced with SELECT-JOIN statements. @Tim has given me an example of one column. I want an example with two columns been filled with two SELECT-JOIN statements.

1 Answer 1

2

You may rephrase this as an INSERT INTO ... SELECT:

INSERT INTO books (gid, type, membernumber, changedate, user)
SELECT
    '2b4493e8-cae8-4624-8177-fcc96553c5be',
    2,
    member,
    '2017-01-03 00:00:00.000',
    'mark'
FROM mem m
INNER JOIN `group` g
    ON m.uid = g.sgroup;

This should fix your syntax error, but now you have to decide whether this insert makes any sense without a WHERE clause. You are hard coding almost every field for each member.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your reply. My next question is, is it possible to do the same with 2 or more Select-Join statements in the same query because i have another issue similar to the first but now with 3 Select-Join statement. Can you show me an example using the query above but lets assume "user" will have SELECT-Join like membernumber. Thanks
@EddyFreeman I don't completely follow your comment, but it looks like a non trivial departure from this question. You may want to ask a new question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.