简体   繁体   English

SQL Server:如何选择现有的ID并将其插入到新的ID字段中

[英]SQL Server: How to select existing IDs and insert them to the new ID field

I have two tables Category and Movie and I have a mapping table MovieCategory (a movie can have one or multiple categories). 我有两个表CategoryMovie和我有一个映射表MovieCategory (电影可以具有一个或多个类别)。

I then noticed that in my table Movie , there's not one movie with multiple categories. 然后我注意到在我的表Movie ,没有一部电影具有多个类别。

So I want to delete the MovieCategory mapping table. 所以我想删除MovieCategory映射表。 But first, to accomplish this, I created a new column IDCategory in my table Movie which references the Category (a movie can now have only one single category). 但是首先,要实现这一点,我在表Movie创建了一个新列IDCategory ,该列引用了Category (电影现在只能具有一个类别)。

And now, my new IDCategory column is null for all my Movie entries, I want to select all the existing Category entries in my mapping table MovieCategory and then insert the selected IDCategory to my new IDCategory column in the Movie table. 而现在,我的新IDCategory列为空我所有的Movie项目,我想选择所有现有的Category在我的映射表条目MovieCategory ,然后插入选定IDCategory到我的新IDCategoryMovie表。

How can I accomplish this? 我该怎么做?

Here are my columns: 这是我的专栏:

MovieCategory 
---------------------
IDMovie    IDCategory
----------------------

Category table has IDCategory and Movie table has IDMovie and the new IDCategory column Category表具有IDCategoryMovie表具有IDMovie和新的IDCategory

This is just a simple UPDATE statement: 这只是一个简单的UPDATE语句:

UPDATE M
SET IDCategory = MC.IDCategory
FROM Movie M
     JOIN MovieCategory MC ON MC.IDMovie = M.ID;

This is one of the basics of SQL; 这是SQL的基础知识之一。 I suggest having a read up on the UPDATE syntax: SQL Update Statement & UPDATE (Transact-SQL) 我建议阅读一下UPDATE语法: SQL Update语句UPDATE(Transact-SQL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM