Home  >  Q&A  >  body text

The title is rewritten as: English translation of "Insert (SELECT & VALUES) together"

<p>I'm trying to insert data into a table, I know two ways: </p> <p>One is to add the row as a value: </p> <pre class="brush:php;toolbar:false;">INSERT INTO db_example.tab_example (id,name,surname,group) VALUES ('','Tom','Hanks','1');</pre> <p>The other is to insert from another table:</p> <pre class="brush:php;toolbar:false;">INSERT INTO db_example.tab_example (id,name,surname) SELECT ID,first_name,last_name FROM db_contacts.tab_mygroup;</pre> <p>But what if I want to simultaneously insert some values ​​from another table (second method) and manually insert some default values ​​(first method). </p> <p>This is what I tried (without success): </p> <pre class="brush:php;toolbar:false;">INSERT INTO db_example.tab_example (id,name,surname,group) VALUES ( SELECT ID FROM db_contacts.tab_mygroup, SELECT first_name FROM db_contacts.tab_mygroup, SELECT last_name FROM db_contacts.tab_mygroup, '1' );</pre> <p>I thought about creating a view table and that might do the trick, but I thought there might be a way to add both. </p> <p>Thank you everyone! Hope I described clearly what I need :)</p>
P粉536532781P粉536532781392 days ago499

reply all(2)I'll reply

  • P粉980815259

    P粉9808152592023-08-25 14:47:08

    Try this

    INSERT INTO db_example.tab_example (id,name,surname)
    SELECT id,first_name,'M. Nega'
    FROM db_contacts.tab_mygroup

    You can use join in the FROM clause. It should work!

    reply
    0
  • P粉373596828

    P粉3735968282023-08-25 11:19:31

    Simply return the literal value from the SELECT statement; add an expression to the SELECT list. For example:

    INSERT INTO db_example.tab_example (id,name,surname,group)
    SELECT ID
         , first_name
         , last_name
         , '1' AS group
      FROM db_contacts.tab_mygroup;

    Follow-up

    Q: Can I use the AS function to select first_name and last_name in the same column? Or do I need another function?

    Answer: If you want to combine the values ​​of first_name and last_name into a single column, you can join them using an expression and Use this expression in the SELECT list, such as

    CONCAT(last_name,', ',first_name')

    or

    CONCAT(first_name,' ',last_name)
    The

    AS keyword has no effect in the context of INSERT ... SELECT, but assigns the expression an Aliases may help future readers.

    INSERT INTO db_example.tab_example (id,name,surname,group,full_name)
    SELECT ID
         , first_name
         , last_name
         , '1' AS group
         , CONCAT(first_name,' ',last_name) AS full_name
      FROM db_contacts.tab_mygroup

    reply
    0
  • Cancelreply