如何从多个表中选择多个列并插入到一个表中 [英] How to select multiple columns from multiple table and insert into one table

查看:116
本文介绍了如何从多个表中选择多个列并插入到一个表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有采取真实的例子。但它与此类似。

假设我有3张桌子。



fruits(id ,名称,颜色,)

鲜花(id,名称,类型)

main_table(id,描述,名称(来自水果表),颜色(来自水果表),名字(来自花桌))y



所有表的id都是主键而不是null身份(1,1)并自动生成



怎么做?



我尝试过:



i使用了外键。但我很困惑我是否应该使用外键或我应该插入该列,因为它在另一个表中

i am not taking real example.but it is similar to this.
suppose i have 3 tables.

fruits(id,name,colour,)
flowers(id,name,type)
main_table(id,description,name(from fruit table),colour(from fruit table),name(from flower table))y

all table's id's are primary key not null identity(1,1) and autogenerated

how to do this?

What I have tried:

i have used foreign key.but i am confused whether i should use foreign key or i should insert that column as it is in another table

推荐答案

Fruits (ID,名称,颜色)

鲜花(Id,名称,类型)

Fruit_Flower(Id,description,FruitsId,FlowersId)



当水果与花朵相连时选择所有水果和所有花朵,反之亦然。



SELECT ff.Id,ff.description ,fr.Name,fl.Name

FRO M Fruit_Flower ff

加入FR上的水果fr.Id = ff.FruitId

加入FL fl.Id = ff.FlowerId



- 使用所需的连接将表连接在一起(有不同类型的连接产生不同的结果集)

- 使用别名(ff,fr,fl是表的别名)

- 选择所需的字段并用别名作为前缀:'#tableAlias。 #field'



如果我误解了你的问题,请道歉。

如果你想选择像union一样的数据 - 使用'select ... into #NewTableName'并指定表名
Fruits (Id, Name, Colour)
Flowers (Id, Name, Type)
Fruit_Flower(Id, description, FruitsId, FlowersId)

To select all fruits and all flowers when a fruit is linked to a flower or vice versa.

SELECT ff.Id, ff.description, fr.Name, fl.Name
FROM Fruit_Flower ff
JOIN Fruits fr on fr.Id = ff.FruitId
JOIN Flowers fl on fl.Id = ff.FlowerId

- join the tables together using the desired join (there are different types of joins yielding different result sets)
- use aliases (ff, fr, fl are aliases to tables)
- select the desired fields and prefix them with an alias : '#tableAlias . #field'

Apologies if I have misunderstood your question.
If you wish to select the data like a union would do - use the 'select... into #NewTableName' and specify the table name


这篇关于如何从多个表中选择多个列并插入到一个表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆