2016-05-13 76 views
3

我有两张表。第一个包含产品,第二个包含产品价格。在第二张表中加入两张ID最高的表

 
**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) 

回答

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) 
+0

但我不想按产品名称'a'过滤。我需要一整套产品。 – Josef

+0

谢谢。有用!!! – Josef

+0

很高兴,但是当表中有很多记录时,这会带来一些性能问题。如果确实有,请尝试像@Tim Biegeleisen这样的其他答案。 – Blank

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