双表条件查询

a1o7rhls  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(233)

我在下面提到了两个表格:

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

通过使用上面的表,我想获取 Val1 以及 Val2 ,但是 Val1 应该是最早的值(考虑到 Date1 )然后匹配 Val1Val2 并以此为基础给予身份。
所需输出:

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
osh3o9ms

osh3o9ms1#

可以使用自联接:

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

此处演示

相关问题