我有两张 table 。第一个包含产品,第二个包含产品价格。
**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 |
So far I can get only for one product but how to get list for all products
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)
最佳答案
试试这个;)
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)
关于mysql - 在第二个表中加入具有最高 ID 的两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37207257/