The title is rewritten as: English translation of "Insert (SELECT & VALUES) together"
P粉536532781
P粉536532781 2023-08-24 16:36:32
0
2
496
<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粉536532781
P粉536532781

reply all(2)
P粉980815259

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!

P粉373596828

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!