【问题标题】:SQL Query to get data from two table [duplicate]SQL查询从两个表中获取数据[重复]
【发布时间】:2015-11-13 17:06:44
【问题描述】:

假设我有一张如下表:

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(of tblEvents) 等于 UserId(of tblUsers)。所以最终的输出应该是下面的格式:

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

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

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

【问题讨论】:

  • 非常基本的问题。寻找INNER JOIN
  • 令人震惊的基本 SQL 问题。在使用 StackOverflow 提出此类问题之前,您至少应该学习 SQL 的基础知识。
  • @MikeGledhill:RTFM 问题现在离题了吗?我认为一个简单的downvote就足够了......

标签: sql-server


【解决方案1】:

这将起作用。使用简单的INNER JOIN

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

【讨论】:

    【解决方案2】:

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

    SELECT tblEvents.Eventid, tblEvents.EventName, tblEvents.UserId ,tblUsers. UserName
    FROM tblEvents INNER JOIN tblUsers ON tblEvents.UserId=tblUsers.UserId
    

    【讨论】:

      【解决方案3】:

      查询:

      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
      

      您可以使用into here 阅读有关creating table 的更多信息

      【讨论】:

        猜你喜欢
        • 2013-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-28
        • 1970-01-01
        • 2012-08-23
        相关资源
        最近更新 更多