Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Problem with INNER JOIN

Posted on 2008-06-26
1
Medium Priority
?
321 Views
Last Modified: 2008-06-26
Hi all,
I have Two tables : "Users" & "UserLogs"
The table Users has all the common fields (ID, Name, Email, etc....)
The table UserLogs has: UserID, UserLogTypeID, CreatedDate.

The point is that if a user for example LogsOn to the website, the system will insert to the UserLogs Table this row:
UserID: 29 (just for the example)
UserLogTypeID: 1 (1 means "LogOn", 2 means "LogOff", etc......)
CreatedDate = now() / GatDate() / etc... :)

OK.
If I want to see what is the last time the user was logged on, I make this query:

SELECT     TOP (1) CreatedDate
FROM          UserLogs
WHERE      (UserLogTypeID = 1) AND (UserID=29)
ORDER BY CreatedDate DESC


Until here it's all good.

But, I want to pull all the users table and insert an extra field called LastLoggedOn.
I try to do this query but I get the results for only the last user and all the others are NULL:

SELECT     Users.ID, Users.Email,  Users.FirstName, Users.LastName, tblLastLogon.CreatedDate AS LastLogon
FROM         Users LEFT INNER JOIN
                          (SELECT     TOP (1) CreatedDate, UserID
                            FROM          UserLogs
                            WHERE      (UserLogTypeID = 1)
                            ORDER BY CreatedDate DESC) AS tblLastLogon ON Users.ID = tblLastLogon.UserID

Please tell me how to fix it.
Thanks
0
Comment
Question by:giligatech
1 Comment
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 2000 total points
ID: 21873258
here we go:
SELECT     u.ID, u.Email,  u.FirstName, u.LastName, ul.CreatedDate AS LastLogon
FROM         Users u
LEFT OUTER JOIN  UserLogs ul
  ON ul.userid = u.id
 AND ul.createddate = ( SELECT MAX(i.creteddate) FROM UserLogs i WHERE i.UserID = u.ID )

Open in new window

0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article, I’ll look at how you can use a backup to start a secondary instance for MongoDB.
One of the most important things in an application is the query performance. This article intends to give you good tips to improve the performance of your queries.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

971 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question