我们说我有一个问题:
select product_id, price, price_day
from products
where price>10
我希望将此查询的结果与自身相结合(例如,如果我想在上一个日中获得相同行的产品价格和价格)
我可以这样做:
select * from
(
select product_id, price, price_day
from products
where price>10
) as r1
join
(
select product_id, price, price_day
from products
where price>10
) as r2
on r1.product_id=r2.product_id and r1.price_day=r2.price_day-1
但正如您所看到的那样,我正在复制原始查询,将其命名为另一个名称,以便将其结果与自身结合起来。
另一种选择是创建一个临时表,但我必须记住删除它。
是否有更优雅的方式将查询结果与自身结合?
答案 0 :(得分:1)
你可以做很多事情,只需要几个选项:
取决于您的情况对性能的重要程度以及您需要使用"最佳"选择会改变。
答案 1 :(得分:1)
自我加入查询将有所帮助
select a.product_ID,a.price
,a.price_day
,b.price as prevdayprice
,b.price_day as prevday
from Table1 a
inner join table1 b
on a.product_ID=b.product_ID and a.price_day = b.price_day+1
where a.price >10
答案 2 :(得分:-1)
只是为了在同一行中获得重复项?
select product_id as id1, price as price1, price_day as priceday1, product_id as id2, price as price2, price_day as priceday2,
from products
where price>10