-4

Lets say i have one table as below :

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

and second table as :

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

How can i get a new table(or result) which has combined results from both.I am only concerned about tblEvents which should just show the UserName from tblUsers where Userid(of tblEvents) is equal to UserId(of tblUsers). So the final output should be in the below format :

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

where UserName comes from tblUsers. I cannot change the primary keys on any of the table.

Edit : UserId is not INT and cannot be used as primary-foreign keys

RelatedRhymes
  • 428
  • 6
  • 26

3 Answers3

1

This will Work. Use simple INNER JOIN.

SELECT te.EventId , te.EventName , te.UserId , tu.UserName
FROM tblEvents te
INNER JOIN tblUsers tu ON te.UserId=te.UserId
Felix Pamittan
  • 31,544
  • 7
  • 41
  • 67
0

Query:

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

If you want to create a new table out of that then:

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

You can read more about creating table using into here

Praveen
  • 8,945
  • 4
  • 31
  • 49
0

Review inner join in SQL and try below query.

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