Search code examples
phpmysqlpdoinsert-select

Need an INSERT ...SELECT statement, but I also want to manually set some fields


I need an insert statement that will do roughly this:

INSERT INTO
    tblContent(postTitle, postBody, postAuthor, postDate, postApproved, fromSite)
     SELECT tblSubmissions.body
            WHERE tblSubmissions.submissionId = 1

But I need to manually supply the rest of the fields. Is this possible? Or do I need to insert once, and then update? If I need to insert, then update, I know that I can probably use PDO::lastInsertId for this, but could someone provide a clear example, please?


Solution

  • It is possible : just inject the values you know into the select clause ;-)

    For example, you could have something like this :

    insert into your_table (field1, field2, field3)
    select 'my_value', field_from_select, 152
    from your_other_table
    where ...
    

    Here, 'my_value' and 152 are values I know before -- and field_from_select is the dynamic field that comes from the select.