用两个表Mysql进行条件查询

时间:2018-05-18 11:28:25

标签: mysql

我在下面提到了两个表:

Table1
ID        key          Val1         Date1
A-1       xyz-ze       AA           2018-10-01 15:16:20
A-1       xyz-ze       AC           2018-10-02 18:19:40
A-2       xyi-ze       BV           2018-07-01 15:16:20
A-2       xyi-ze       CR           2018-03-01 19:22:37
A-2       xyi-ze       BR           2018-10-03 21:17:24

Table2
ID        key          Val2         Date2
A-1       xyz-ze       AA           2018-10-01 15:16:20
A-2       xyi-ze       BR           2018-10-03 22:47:56

通过使用上面的表格,我想要提取Val1Val2,但Val1应该是最旧的值(考虑Date1),然后匹配Val1使用Val2并根据该状态提供状态。

必需的输出:

ID    key     Val1  Val2 Date1                Date2                Status
A-1   xyz-ze  AA    AA   2018-10-01 15:16:20  2018-10-01 15:16:20  TRUE
A-2   xyi-ze  CR    BR   2018-03-01 19:22:37  2018-10-01 15:16:20  FALSE

1 个答案:

答案 0 :(得分:1)

您可以使用自我加入:

SELECT t1.ID, t1.`key`, t1.Val1,  t1.Date1, t2.Date1
FROM Table1 t1
LEFT JOIN Table1 t2 
   ON t1.ID = t2.ID AND t1.`key` = t2.`key` AND t2.Date1 < t1.Date1

得到:

ID  key     Val1    Date1                   Date1
----------------------------------------------------------------
A-1 xyz-ze  AA      2018-10-01T15:16:20Z    (null)
A-1 xyz-ze  AC      2018-10-02T18:19:40Z    2018-10-01T15:16:20Z
A-2 xyi-ze  CR      2018-03-01T19:22:37Z    (null)
A-2 xyi-ze  BV      2018-07-01T15:16:20Z    2018-03-01T19:22:37Z
A-2 xyi-ze  BR      2018-10-03T21:17:24Z    2018-03-01T19:22:37Z
A-2 xyi-ze  BR      2018-10-03T21:17:24Z    2018-07-01T15:16:20Z

通过这种方式,您可以使用以下方法确定最早的每组记录:

WHERE t2.Date1 IS NULL

因此,最终的查询将是:

SELECT t1.ID, t1.`key`, t1.Val1, t3.Val2, t1.Date1, t3.Date2
FROM Table1 t1
LEFT JOIN Table1 t2 ON t1.ID = t2.ID AND t1.`key` = t2.`key` AND t2.Date1 < t1.Date1
INNER JOIN Table2 AS t3 ON t1.ID = t3.ID AND t1.`key` = t3.`key` 
WHERE t2.Date1 IS NULL

Demo here