在第二个表中加入两个具有最高ID的表

时间:2016-05-13 10:11:02

标签: mysql left-join

我有两张桌子。首先包含产品,第二个包含产品价格。

**Table1** 
productName  |
--------------
     a       | 
     b       |  
     c       |  


**Table2**  
productName  | Price | ID   |
-----------------------------
     a       |   3   |  1   |
     b       |   4   |  2   |
     a       |   1   |  3   |
     b       |   2   |  4   |
     c       |   1   |  5   |    


I need to get products with last price. Product with last price have in second table have the highest ID.

The output should be like:


**Output**    
productName  | Price |
----------------------
     a       |   3   |  
     b       |   2   |
     c       |   1   |

到目前为止,我只能获得一种产品,但如何获得所有产品的清单

SELECT table1.productname, table2.price
FROM table1
LEFT JOIN table2 ON table1.productname = table2.productname
WHERE table1.productname = 'a' AND table1.ID = (SELECT id FROM table2 WHERE productname = 'b' ORDER BY id DESC LIMIT 1)

2 个答案:

答案 0 :(得分:3)

试试这个;)

SELECT table1.productname, table2.price
FROM table1
LEFT JOIN table2 ON table1.productname = table2.productname
WHERE (table2.productname, table2.ID) in (select productName, max(id) from table2 group by productName)

答案 1 :(得分:3)

SELECT t1.productName, COALESCE(t2b.Price, 'NA')
FROM Table1 t1
LEFT JOIN
(
    SELECT productName, MAX(ID) AS maxID
    FROM Table2
    GROUP BY productName
) t2a
    ON t1.productName = t2a.productName
LEFT JOIN Table2 t2b
    ON t2a.productName = t2b.productName AND t2a.maxID = t2b.ID