简体   繁体   English

从子查询获取列

[英]Get Column From Subquery

I currently have the following (simplified) sql which selects user data from a main table table1 . 我目前有以下(简化)的sql从主表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. 这两个表通过用户ID列关联。 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) ? 我的问题是,有没有办法返回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. 仅供参考:此sql被解析为自定义PDO函数,因此无需警告mysql函数的不安全性。

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. 您将需要使用HAVING而不是WHERE因为您正在使用别名进行比较。 If your query cannot use HAVING due to other factors then you'll need to repeat the subquery (not ideal). 如果您的查询由于其他因素而无法使用HAVING ,则需要重复子查询(不理想)。

If you want to show the aggregation result, you should select from the aggregation. 如果要显示聚合结果,则应从聚合中选择。 In order to do so group your aggregation by userid. 为此,请按用户ID对汇总进行分组。 You can use HAVING to only select desired ones. 您可以使用HAVING仅选择所需的选项。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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