Files
firestuff/2011-11-29-converting-subselects-to-joins-part-2.html

36 lines
1.1 KiB
HTML
Raw Normal View History

2019-04-15 03:51:32 +00:00
<!--# set var="title" value="Converting subselects to joins, part 2" -->
2019-04-25 02:45:09 +00:00
<!--# set var="date" value="2011-11-29" -->
2019-04-15 03:51:32 +00:00
<!--# include file="include/top.html" -->
<p><a href="2011-07-12-converting-subselects-to-joins.html">I previously discussed this in depth</a>. However, today I saw a case that I didn't cover:</p>
<p>You have a table of Users and a table of Logins, with a row for each user login event. You're looking for users that have logged in within the last 31 days. The initial version of this I saw used a derived table:</p>
<pre><code>SELECT
UserId,
LastLogin
FROM Users
JOIN (
SELECT
UserId,
DATEDIFF(NOW(), MAX(TimeStamp)) AS LastLogin
FROM Logins
GROUP BY UserId
) AS Temp USING (UserId)
2019-04-24 06:02:16 +00:00
WHERE LastLogin &lt;= 31;
2019-04-15 03:51:32 +00:00
</code></pre>
<p>We can convert this to a simple JOIN with the magic of HAVING. HAVING is like WHERE, but applies after aggregation:</p>
<pre><code>SELECT
UserId,
DATEDIFF(NOW(), MAX(TimeStamp)) AS LastLogin
FROM Users
JOIN Logins USING (UserId)
GROUP BY UserId
2019-04-24 06:02:16 +00:00
HAVING LastLogin &lt;= 31;
2019-04-15 03:51:32 +00:00
</code></pre>
<!--# include file="include/bottom.html" -->