根据子查询中的选定列值从表中选择记录

时间:2018-05-04 10:42:02

标签: mysql sql

我有一个查询选择某些列值作为结果集。

根据该子查询产生的一些列值,我想从另一个表中选择记录。

EG。

POST                   |    Start DATE  |  End DATE   |  MONTHS
---------------------------------------------------------------
Senior Software Engg.  |    2018-04-18  |   -         |
Software Engg.         |    2017-04-18  |  2018-04-18 |  12
Assoc. Software Engg.  |    2016-04-18  |  2017-04-18 |  12

我有以下来自此查询的结果集:

SELECT `POST`, 
    `DATE`,
    IFNULL(END_DATE,'Running') AS END_DATE,
    IFNULL(MONTH,'Running') AS MONTH, user
    FROM
        (
            SELECT `POST`, 
            `DATE`,
            @prev AS END_DATE,
            TIMESTAMPDIFF(month,DATE, IFNULL(@prev, CURDATE())) AS MONTH,
            @prev := T.DATE AS VarDate, user
            FROM (
            SELECT DISTINCT designation_id as id, d.title as POST, DATE(dt_datetime) as DATE, u.id as user
            FROM users_history_check u
            INNER JOIN
            designations d 
            ON d.id = u.designation_id
            WHERE u.id = $userID
            ORDER BY DATE DESC) T, (SELECT @prev:=null) R
        ) T1

我想根据每行中的Start DATEEND DATE值从其他表中提取记录。

预期产出:

POST                   |    Start DATE  |  End DATE   |  MONTHS |  Team
-------------------------------------------------------------------------
Senior Software Engg.  |    2018-04-18  |   -         |  0      | Research
Software Engg.         |    2017-04-18  |  2018-04-18 |  12     | Finance
Assoc. Software Engg.  |    2016-04-18  |  2017-04-18 |  12     | Finance

以下是我想要获取团队记录的表格:

user_team

date         |    team       |   users_id
-------------------------------------------------
2016-04-18   |    Finance    |   1
2017-05-18   |    Finance    |   1
2018-04-18   |    Research   |   1

如何在单个查询中执行此操作?

非常感谢任何帮助。感谢。

0 个答案:

没有答案