问题
I have two tables in MSSQL Server 2012 and would like to combine them into one new table. They are linked by the column messageID. The first table (Message) has
messageID
sender
date
The second table(recipientInfo) has
messageID
recipient
The main problem is that in Message the messageID is the primary key and thus unique. In recipientInfo the messageID is not unique (because one message can have multiple recipients). I'd like to have a new table with either
- One row per message, with recipients concatenated in one column
- Multiple rows per message, when there are multiple recipients (one recipient per row)
回答1:
Maybe something like this (if you are using MSSQL 2005+):
CREATE TABLE NewTable
(
messageID INT,
sender VARCHAR(100),
recipient VARCHAR(MAX),
date DATETIME
)
INSERT INTO NewTable(messageID,sender,recipient,date)
SELECT
[Message].messageID,
[Message].sender,
STUFF
(
(
SELECT
',' +recipient
FROM
recipientInfo
WHERE
recipientInfo.messageID=[Message].messageID
FOR XML PATH('')
)
,1,1,'') AS recipient,
[Message].date
FROM
[Message]
回答2:
Do you want to create a view and leave the existing tables there? Or do you want to combine the two tables permanently?
SELECT m.messageID, m.sender, m.date, r.recipient
INTO New_Table
FROM Message m LEFT OUTER JOIN
recipientinfo r on m.messageID = r.messageID
回答3:
select msg.messageID, msg.sender, rep.recipient, msg.date
from Message msg
left outer join recipientInfo rep on msg.messageID = rep.messageID
回答4:
you may need to sort the spellings out here
select sender,date,( select recipient+chr(10) from receipientInfo as r where r.messageid = m.messageid order by r.recipient FOR XML PATH ('')) as receipents from message as m
回答5:
you can just merge the two tables
https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
this might be something more suited and there are more ways than one to do it
来源:https://stackoverflow.com/questions/10294846/combine-two-tables-in-one