MySQL-如何创建一个新表,该表是两个现有表的主键的联接
我有两个现有表,它们具有不同的字段,但主 ID(varchar
,而不是 int
)除外。我想创建第三个表,它本质上是这两个表的合并,这样对于给定的主键,我将所有字段都放在一个表中。
这怎么能做到呢?
I have two existing tables, with different fields, except for Primary ID (a varchar
, not an int
). I want to create a third table which is essentially a merge of these two, such that for a given Primary Key I have all fields in one table.
How can this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要获取视图,请执行相同的操作,只不过将“TABLE”替换为“VIEW”。如果您使用表而不是视图,请确保添加主键,因为默认情况下不会添加主键。
To get a view, do the same except replace "TABLE" with "VIEW". If you go with the table rather than the view, make sure to add a primary key as that will not be added by default.
如果您确定两个表中对于给定的主 ID 都只有一行,那么这应该可行:
如果您实际上不需要它们,您可能希望从字段列表中省略 tablea 和 tableb 的主 ID 字段(在本例中)由于
tablea.primaryID = tableb.primaryID
条件,查询两者将包含相同的值)。VIEW
的语法也相对相似。If you are sure you have one and exactly one row in both tables for a given primary ID, then this should work:
You might want to omit tablea's and tableb's primary ID field from the field list if you do not actually need them (in this query both will contain the same value due to the
tablea.primaryID = tableb.primaryID
condition).The syntax is relatively similar for a
VIEW
as well.对于 MS SQL 使用这个
For MS SQL use this
为什么要创建一个新表?为什么不在需要数据时执行查询呢?如果您只是通过主键连接两个表,那么您的大部分数据访问时间将花在将数据编组回您的应用程序上。你不会在入桌前节省太多时间,而且会占用很多空间。另外,您正在瞄准您的大脚趾,只是在等待第一次更新源表并忘记运行更新脚本以将更改复制到连接表。重复数据是邪恶,但有时它是必要的。这听起来不像是那些时候。
Why are you creating a new table? Why don't you just execute a query whenever you need the data? If you're just joining two tables on their primary key, then the majority of your data access time is going to be spent marshalling the data back to your application. You're not going to be saving much time pre-joining the tables, and you'll be eating a lot of space. Plus, you're taking aim at your big toe, just waiting for the first time you update your source tables and forget to run your update script to copy the changes to your joined table. Duplicate data is evil, but sometimes it's necessary. This doesn't sound like one of those times.