使用mysql或mariadb使用MAX()子查询值连接两个表

时间:2018-01-30 07:07:41

标签: mysql join max mariadb

我在mysql / mariadb db中有两个表。两者都有MAX(历史)值来维护修订。这些表已加入,因此tableB引用了tableA

我可以在tableB上进行基本查找以获取每条记录的最新版本并将其加入tableA

表A

|product|value|history|
|alpha  |a    |0      |
|beta   |z    |0      |
|delta  |s    |0      |

tableB的

|type   |product|history|
|blue   |alpha  |0      |
|blue   |beta   |1      |
|green  |alpha  |0      |
|green  |delta  |1      |  

MySQL的

SELECT DISTINCT 
  `b`.`type` AS `b_type`,  
  `b`.`product` AS `b_prod`,
  `b`.`history` AS `b_hist`,
  `a`.`value`   AS `a_val`,
  `a`.`history` AS `a_hist`
from `myTable`.`tableB` `b`  
JOIN (
  SELECT type, MAX(history) history
  FROM `myTable`.`tableB`
  GROUP BY type
 ) `tabB` ON `b`.`history` =`tabB`.`history` AND `b`.`type` =`tabB`.`type`
 JOIN `myTable`.`tableA` `a` 
 ON `a`.`product` = `b`.`product`

返回

|b_type|b_prod|b_hist|a_val|a_hist|
|blue  |beta  |1     |a    |0     |
|green |delta |1     |s    |0     |

现在我想将历史元素添加到tableA

|product|value|history|
|alpha  |a    |0      |
|alpha  |b    |1      |
|beta   |z    |0      |
|beta   |y    |1      | 
|delta  |s    |0      |
|delta  |t    |1      |     

如何在JOIN上添加第二个tableA来过滤MAX(HISTORY)个结果

JOIN (
      SELECT product, MAX(history) history
      FROM `myTable`.`tableA`
      GROUP BY product
     ) `tabA` ON `a`.`history` =`tabA`.`history` AND `a`.`product` 
 =`tabA`.`product` 

所以返回的值看起来像

|b_type|b_prod|b_hist|a_val|a_hist|
|blue  |beta  |1     |b    |1     |
|green |delta |1     |t    |1     |

0 个答案:

没有答案