sql server将数据从table1插入table2,其中table1 = table3数据

时间:2011-01-13 21:36:06

标签: sql sql-server sql-server-2005 tsql

我试图在表A中插入表B中与TAble C中的数据匹配的唯一数据但是我一直在违反主键错误并且不确定我做错了什么 表A - bookfeed 表B - bookF 表C - bookStats

INSERT INTO bookFeed
 (entryId,feed,entryContent,pubDate,authorName,authorId,age,
  sex,locale,pic,fanPage, faceTitle,feedtype,searchterm,clientId,dateadded)
SELECT DISTINCT b.entryId,b.feed,b.entryContent,b.pubDate,b.authorName,
    b.authorId,b.age,b.sex,b.locale,b.pic,b.fanPage,b.faceTitle,b.feedtype,
    b.searchterm, b.clientId,b.dateadded 
  FROM bookF as b
  INNER JOIN bookStats as a on a.feed = b.feed 
       WHERE NOT EXISTS (SELECT * 
                           FROM bookFeed as c 
                          WHERE c.entryId = b.entryId)

表A bookFeed在entryId上有一个主键

2 个答案:

答案 0 :(得分:2)

看起来在表bookF中,每个entryId都有重复的记录 如果您只想要一个entryId(受bookFeed上的PK限制),您可以使用它。在ROW_NUMBER中调整顺序以适合

insert into bookFeed (
    entryId,feed,entryContent,pubDate,authorName,authorId,age,
    sex,locale,pic,fanPage,faceTitle,feedtype,searchterm,clientId,dateadded)
select
    entryId,feed,entryContent,pubDate,authorName,authorId,age,
    sex,locale,pic,fanPage,faceTitle,feedtype,searchterm, clientId,dateadded
from
(
    select rn=Row_number() over (partition by b.entryId order by b.entryId),
        b.entryId,b.feed,b.entryContent,b.pubDate,b.authorName,b.authorId,b.age,
        b.sex,b.locale,b.pic,b.fanPage,b.faceTitle,b.feedtype,b.searchterm, b.clientId,b.dateadded
    from bookF as b
    inner join bookStats as a on a.feed = b.feed
    left join bookFeed as c on c.entryId=b.entryId
    where c.entryId is null
) X
where rn=1

答案 1 :(得分:1)

更新:尝试此查询并查看是否有效,查看数据并查看是否存在重复,这意味着所有条目的条目ID应与当前条目不同 -

SELECT b.entryId,b.feed,b.entryContent,b.pubDate,b.authorName,
    b.authorId,b.age,b.sex,b.locale,b.pic,b.fanPage,b.faceTitle,b.feedtype,
    b.searchterm, b.clientId,b.dateadded 
  FROM bookF as b
  INNER JOIN bookStats as a on a.feed = b.feed 
       WHERE b.entryId IN (SELECT distinct entryid 
                           FROM bookFeed)

我认为您正在尝试插入作为主键的条目ID(检查尝试插入的值是否不重复,null或违反任何其他主键约束)...所以要么不要尝试插入如果它自动填充或者你想要插入它然后打开身份插入...再试一次...

但理想情况下,你的id应该被计算(自动增量或其他东西),永远不要直接插入。