1

Let's say I have a query:

select product_id, price, price_day
from products
where price>10

and I want to join the result of this query with itself (if for example I want to get in the same row product's price and the price in previous day)

I can do this:

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

but as you can see I am copying the original query, naming it a different name just to join its result with itself.

Another option is to create a temp table but then I have to remember to remove it.

Is there a more elegant way to join the result of a query with itself?

Max Segal
  • 1,955
  • 1
  • 24
  • 53

3 Answers3

2

self join query will help

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
Max Segal
  • 1,955
  • 1
  • 24
  • 53
kostas
  • 461
  • 5
  • 13
1

You could do a bunch of things, just a few options could be:

  • Just let mysql handle the optimization
    • this will likely work fine until you hit many rows
  • Make a view for your base query and use that
    • could increase performance but mostly increases readability (if done right)
  • Use a table (non temporary) and insert your initial rows in there. (unfortunately you cannot refer to a temporary table more than once in a query)
    • this will likely be more expensive performance wise until a certain number of rows is reached.

Depending on how important performance is for your situation and how many rows you need to work with the "best" choice would change.

Community
  • 1
  • 1
Kris
  • 40,604
  • 9
  • 72
  • 101
-1

Just to get duplicates in the same row?

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
user3791775
  • 426
  • 3
  • 5