SQL Query从两个表中获取数据

时间:2015-08-20 07:13:04

标签: sql-server

假设我有一张表如下:

Create table tblEvents
(
Eventid int primary key,
EventName nvarchar(20),
UserId nvarchar(5)
)

和第二个表格如下:

Create table tblUsers
(
Id int primary key,
UserId nvarchar(5),
Username nvarchar(20),
)

我如何得到一个新的表(或结果),它结合了两者的结果。我只关心tblEvents,它应该只显示来自tblUsers的UserName,其中Userid(tblEvents)等于UserId(of tblUsers)。因此最终输出应采用以下格式:

EventId | EventName | UserId | UserName
--------|-----------|--------|---------
        |           |        | 

其中UserName来自tblUsers。 我无法更改任何表格上的主键。

编辑:UserId不是INT,不能用作主外键

3 个答案:

答案 0 :(得分:1)

这将有效。使用简单的INNER JOIN

SELECT te.EventId , te.EventName , te.UserId , tu.UserName
FROM tblEvents te
INNER JOIN tblUsers tu ON te.UserId=te.UserId

答案 1 :(得分:0)

查询:

select 
    e.Eventid,
    e.EventName,
    e.UserId,
    u.Username
from  tblEvents e
join tblUsers u on e.UserId = u.UserId

如果你想创建一个新表,那么:

select 
    e.Eventid,
    e.EventName,
    e.UserId,
    u.Username
into new_table
from  tblEvents e
join tblUsers u on e.UserId = u.UserId

您可以使用creating table here

详细了解into

答案 2 :(得分:0)

在SQL中查看内部联接并尝试以下查询。

SELECT tblEvents.Eventid, tblEvents.EventName, tblEvents.UserId ,tblUsers. UserName
FROM tblEvents INNER JOIN tblUsers ON tblEvents.UserId=tblUsers.UserId
相关问题