使用辅助表连接两个表

时间:2017-05-15 11:40:55

标签: sql tsql inner-join

我有两个表,ChatMessage。另一个表名为chat_message_join。架构如下所示:

+-----------+  +--------------+  +---------------------+
| chat      |  | message      |  |chat_message_join    |
+-----------+  +--------------+  |---------------------+
| chat_ID   |  |message_ID    |  |chat_ID              |
| contact   |  |message       |  |message_ID           |
+-----------+  -------------- +  +---------------------+

现在我希望另一个表格包含来自contact表的chat和来自message表的message。新表模式如下所示:

+-----------+
|message_new|
+-----------+
|contact    |
|message    |
+-----------+

T-SQL查询会是什么样的?

2 个答案:

答案 0 :(得分:0)

此查询应该可以帮助您。

select chat.contact, message.message from chat 
inner join chat_message_join on chat.chat_ID = chat_message_join.chat_ID
inner join message on chat_message_join.message_ID = message.message_ID

要插入新表,请使用

insert into whatever_table (contact,message)
select chat.contact, message.message from chat 
inner join chat_message_join on chat.chat_ID = chat_message_join.chat_ID
inner join message on chat_message_join.message_ID = message.message_ID

答案 1 :(得分:0)

如果我理解你的问题,那就像

SELECT a.Contact
,c.message
into newtable
from chat a
inner join chat_message_join b on a.chat_ID=b.chat_ID
inner join chat_ID c on c.messageID=b.messageID