加入第二个 table 中具有最高 ID 的两个 table
Join two tables with highest ID in second 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 |
到目前为止,我只能获取一种产品,但如何获取所有产品的列表
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)
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
我有两张桌子。第一个包含产品,第二个包含产品价格。
**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)
试试这个;)
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)
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