The title is rewritten as: English translation of "Insert (SELECT & VALUES) together"
P粉536532781
2023-08-24 16:36:32
<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>
Try this
You can use join in the FROM clause. It should work!
Simply return the literal value from the SELECT statement; add an expression to the SELECT list. For example:
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
andlast_name
into a single column, you can join them using an expression and Use this expression in the SELECT list, such asor
TheAS
keyword has no effect in the context ofINSERT ... SELECT
, but assigns the expression an Aliases may help future readers.