在sql

时间:2018-04-07 02:07:48

标签: mysql subquery

我有一些表格如下所示

用户

-----------------------------------------
| id | policyId | createdAt | updatedAt |
-----------------------------------------
| 1  |    1     |  2017/8/5 |  2017/8/5 |
| 2  |    1     |  2016/4/5 |  2017/8/5 |
| 3  |    2     |  2017/7/2 |  2017/8/5 |
| 4  |    2     |  2018/8/5 |  2017/8/5 |
-----------------------------------------

策略

------------------------------------------
| id | companyId | createdAt | updatedAt |
------------------------------------------
| 1  |    1      |  2017/8/5 |  2017/8/5 |
| 2  |    2      |  2016/4/5 |  2017/8/5 |
------------------------------------------

公司

-----------------------------------------
| id | policyId | createdAt | updatedAt |
-----------------------------------------
| 1  |    2     |  2017/8/5 |  2017/8/5 |
| 2  |    1     |  2016/4/5 |  2017/8/5 |
-----------------------------------------

我需要回答这个问题“每个拥有最旧帐户的公司的用户ID是多少。所以输出应该是这样的。

输出

----------------------------------
| CompanyId | UserId | CreatedAt |
----------------------------------
|     1     |   2    |  2016/4/5 |   
|     2     |   3    |  2017/7/2 |
----------------------------------

到目前为止我得到的东西看起来像这样,但我知道这不是正确的。

SELECT c.id, MIN(u.createdAt) FROM companies as c
    JOIN policies as p on p.companyId = c.id
    JOIN users as u on u.policyId = p.id
    GROUP BY c.id;

这似乎让我获得了每个公司用户最早的日期,但我不确定如何将用户关联到该日期以获取用户ID。我认为上面的查询可能必须是一个子查询,但就我的sql知识而言,这就是。

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:0)

SELECT p.company_id, u.user_id, MIN(u.createdAt) FROM policies p, user_u,
(SELECT min(createdAt) as minDate, policy_id as policyId from users
 GROUP BY policy_id) as sub
WHERE p.id = u.policy_id
AND sub.minDate = u.createdAt
AND sub.policy_id = u.policyId;

答案 1 :(得分:0)

它会给你预期的输出但是一些硬编码方式

SELECT c.id as companyid,u.id as userid, MIN(u.createdAt) as createdAt FROM company as c
    JOIN policies as p on p.cmpid = c.id
    JOIN users as u on u.policyId = p.id
    GROUP BY c.id,u.id order by MIN(u.createdAt) asc limit 2;

答案 2 :(得分:0)

我需要将整个查询加入到自身中,并通过comapny id和createdAt列加入。

在此处查看演示:http://sqlfiddle.com/#!9/6f4ea7/22

POST()