insert one column data from a table into other table, but the other column data will be specified dynamically

霸气de小男生 提交于 2019-12-25 10:16:41

问题


i have 2 tables. TABLE A COLUMNS - aid , aname TABLE B COLUMNS - bid , bname

from table A, i will pick up data from column 'aid', AND insert it in 'bid' column of table B , but in bname column of table B, i will insert a new value. how do i do this?

create table A(aid int,aname char)

insert into A values(111, 'e') 


create table B(bid int, bname char)


insert into B (bid,bname)

bid will take value from the query : select aid from a bname will get a new value -m

expected result should be : THE TABLE B WILL HAVE :

bid bname --- ----- 111 m


回答1:


Try this:

insert into b (bid, bname) select aid, 'm' as bname_fixed_val from a

Two facts enabled the solution above:

  1. The insert .. select clause allows you to insert the values returned with any select.
  2. You can return constant values as fields with select, like for instance:

    SELECT 0 as id, 'John' as name
    

Combining these two points together, I used an insert..select clause to select the field value from the first table (aid), along with a constant value for the second field (m). The AS bname_fixed_val clause is simply a field alias, and can be omitted.

For more information on SQL, here 's a link: http://www8.silversand.net/techdoc/teachsql/index.htm, although googling it wouldn't hurt also.



来源:https://stackoverflow.com/questions/5196116/insert-one-column-data-from-a-table-into-other-table-but-the-other-column-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!