将最新记录与表格相结合

时间:2017-12-23 09:58:06

标签: mysql sql database

我正在使用mysql,我有以下两个表:

产品

| id | name      |
|----|-----------|
| 1  | Product 1 |
| 2  | Product 2 |
| 3  | Product 3 |

价格

| id | Product_id | created_at          | prices |
|----|------------|---------------------|--------|
| 1  | 1          | 2017-12-23 08:32:11 | 10     |
| 2  | 1          | 2017-11-21 03:33:10 | 12     |
| 3  | 2          | 2017-12-23 08:32:11 | 43     |
| 4  | 2          | 2017-11-21 03:33:10 | 23     |
| 5  | 3          | 2017-12-23 08:32:11 | 78     |
| 6  | 3          | 2017-11-21 03:33:10 | 34     |

如果我这样做:

SELECT * FROM prices WHERE prices.id IN ( SELECT MAX(prices.id) FROM prices GROUP BY prices.created_at ) 

这给了我每个product_id的最后价格:

| id | Product_id | created_at          | prices |
|----|------------|---------------------|--------|
| 1  | 1          | 2017-12-23 08:32:11 | 10     |
| 3  | 2          | 2017-12-23 08:32:11 | 43     |
| 5  | 3          | 2017-12-23 08:32:11 | 78     |

我希望所有产品的最终结果具有最新价格,如下所示:

| id | name      | product_id | created_at          | prices |
|----|-----------|------------|---------------------|--------|
| 1  | Product 1 | 1          | 2017-12-23 08:32:11 | 10     |
| 2  | Product 2 | 2          | 2017-12-23 08:32:11 | 43     |
| 3  | Product 3 | 3          | 2017-12-23 08:32:11 | 78     |

但是,我不确定如何结合:

select * from products

SELECT * FROM prices WHERE prices.id IN ( SELECT MAX(prices.id) FROM prices GROUP BY prices.created_at ) 

我非常感谢您的回复!

3 个答案:

答案 0 :(得分:1)

假设您的第一个查询提供了预期结果,请使用join

SELECT p.*,d.name FROM prices p
inner join product d 
on d.id=p.product_id
WHERE 
p.id IN 
    ( SELECT MAX(prices.id) FROM prices GROUP BY prices.created_at ) 

如果您认为price中的产品ID未在product中映射,请使用left join代替inner join

答案 1 :(得分:0)

我认为您已获得产品名称的最高总价,因此下面是根据您给定的表格查询

选择price.id,products.id,products.product,sum(prices.prices)作为总价格从价格加入产品price.id = products.id group by price.id order by Totalprices desc limit 1

希望对你有帮助

答案 2 :(得分:0)

假设最新的价格是最近创建的价格并由prices.created_at值描述,为了获得最新价格,您可以更好地依赖prices.created_at,而不是假设prices.id的时间顺序排序1}}(自动增量),如:

SELECT products.id, products.name, prices.created_at, prices.prices
FROM products 
INNER JOIN prices ON products.id=prices.product_id
INNER JOIN 
(SELECT product_id, MAX(created_at) AS created_at FROM prices GROUP BY product_id) AS LATEST_PRICES
on prices.product_id=LATEST_PRICES.product_id
-- WHERE prices.created_at = LATEST_PRICES.created_at
AND prices.created_at = LATEST_PRICES.created_at