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

标签 mysql left-join

我有两张 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/

相关文章:

mysql - SQL查询分组按日期洗牌

sql - SQL Server 2012 是否有延迟连接

mysql - GROUP BY 导致 ORDER BY 不起作用

php - 这个 MySQL CASE SELECT 有更好的方法吗?

mysql - 菜鸟mysql加入问题

mysql - 在 MySQL 中使用登录时间戳统计活跃用户

mysql - 当mysql innodb数据库非常大时,数据库性能如何受到影响?

mysql - phpmyadmin 错误

MySQL 在设定时间内查询事务

MySQL 连接和空值