我有两个Mysql表:
products
,ID,姓名,链接products-prices
包含id,id_prod,价格,可用性和日期在第二个中,正如您所看到的,我可以根据更新的时间为同一产品提供更多价格,我想要做的是让一个查询向我展示最低价格,平均价格和最新价格价钱。我可以在一个查询中获得前两个(最低和平均价格)和另一个查询中的最新价格,但我不知道如何连接它们或者是否有其他方式。
我的第一个查询如下:
SELECT
`products`.id AS ids, `products`.name, `products`.link,
`products-prices`.id AS id_p, `products-prices`.price,
`products-prices`.availability, `products-prices`.date,
AVG(`products-prices`.price) AS medie,
MIN(`products-prices`.price) AS minim
FROM
`products-prices`
INNER JOIN
`products` ON `products`.id = `products-prices`.id_produs
GROUP BY
ids
ORDER BY
ids
,第二个是:
SELECT *
FROM `products-prices`
WHERE date IN (SELECT DISTINCT MAX(date) max_date
FROM `products-prices`
GROUP BY id_produs)
你能告诉我如何将它们结合起来吗?非常感谢你!
(我不知道UNION是如何工作的,如果有效,我会试试)
//编辑:我还有另外一个问题,我可以在数据库中没有最新条目的情况下获取MIN,AVG值吗?
答案 0 :(得分:0)
您可以使用子选择作为最大日期
select
`products`.id AS ids,
`products`.name,
`products`.link,
t.date,
t.price,
t.availability,
AVG(`products-prices`.price) AS medie,
MIN(`products-prices`.price) AS minim
from `products`
inner join `products-prices` ON `products`.id=`products-prices`.id_produs
inner join ( )
select id_produs, date, price, availability
from `products-prices`
where ( id_produs, date ) = (
select id_produs, max(date) as max_date
from `products-prices`
group by id ) t on t.id_produs = `products`.id_prod
答案 1 :(得分:0)
这是一个未经测试的解决方案,如果有帮助请告诉我
SELECT
`products`.id AS ids, `products`.name, `products`.link,
`products-prices`.id AS id_p, `products-prices`.price,
`products-prices`.availability, `products-prices`.date,
AVG(`products-prices`.price) AS medie,
MIN(`products-prices`.price) AS minim,
latest.`date` as latest_date,
latest.price as latest_price
FROM
`products-prices`
INNER JOIN
`products` ON `products`.id = `products-prices`.id_produs
INNER JOIN
(select id_produs, price, `date`
from `products-prices` t1
where not exists (select 1
from `products-prices` t2
where t1.`date` < t2.`date` and t1.id_produs = t2.id_produs)
group by id_produs
) latest
ON
latest.id_produs = products.id
GROUP BY
ids
ORDER BY
ids