简体   繁体   中英

Get Column From Subquery

I currently have the following (simplified) sql which selects user data from a main table table1 . This query only select users who have not logged in since a given date. I use a sub query as the login table is separate from the main table. The two tables relate via a user ID column. This works perfectly.

// sql to get all records that haven't logged in since date above
$sql = "SELECT t1.*
FROM table1 t1
WHERE '2016-08-01' > (SELECT MAX(t2.DateCol)
                 FROM table2 t2
                 WHERE t2.userId= t1.userId)";

My question is, is there a way of returning the value of MAX(t2.DateCol) ? I tired this but is didn't reconise the column

$sql = "SELECT t1.*, MAX(t2.DateCol) ....

FYI: This sql is parsed into a custom PDO function so no need to warn about insecurities of mysql functions.

A quick solution (not knowing your skillset or data setup) - Move the sub-query in scope.

$sql = "SELECT t1.*,
(SELECT MAX(t2.DateCol)
                 FROM table2 t2
                 WHERE t2.userId= t1.userId) AS LastLogin
FROM table1 t1
HAVING '2016-08-01' > LastLogin ";

You will need to use HAVING instead of WHERE because you are comparing using an alias. If your query cannot use HAVING due to other factors then you'll need to repeat the subquery (not ideal).

If you want to show the aggregation result, you should select from the aggregation. In order to do so group your aggregation by userid. You can use HAVING to only select desired ones.

select t1.*, t2.max_datecol
from table1 t1
join
(
  select userid, max(datecol) as max_datecol
  from table2
  group by userid
  having max(datecol) < date '2016-08-01'
) t2 on t2.userid = t1.userid;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM