2015-01-11 2 views
0

가격이 최대로 증가한 시간을 선택하는 가장 효율적인 방법은 무엇입니까? [하단 구조]mysql 상관 하위 쿼리 : select field1 max (field2)

- 최대 가격 상승

select p1.pricetime, max(p2.price) maxnext 
from prices p1 inner join prices p2 on p2.id > p1.id 
group by p1.pricetime 

p2.pricetime가 무엇 얻을 여기서 각 p1.pricetime위한 p2.price = 최대 (p2.price)?

- 최대 가격의 시간을 얻을 당신이 MSSQL에서이 같은 것을 할 수있는 확신 만 다중 행 테이블 에 대한 끔찍하게 비효율적 인 방법입니다

select p3.pricetime, x.maxnext 
from prices p3 inner join 

(select p1.pricetime, max(p2.price) maxnext 
from prices p1 inner join prices p2 on p2.id > p1.id 
group by p1.pricetime) x 

on x.maxnext = p3.price and p3.id > p1.id 

:

select p2.pricetime from 
(select p1.pricetime, max(p2.price) maxnext 
from prices p1 inner join prices p2 on p2.id > p1.id 
group by p1.pricetime) x ... 

하위 쿼리 외부에서 하위 쿼리 별칭에 액세스합니까?

- 구조 :

CREATE TABLE `prices` (
    `id` int(11) NOT NULL DEFAULT '0', 
    `pricetime` varchar(19) DEFAULT NULL, 
    `price` decimal(10,8) DEFAULT NULL 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

LOCK TABLES `prices` WRITE; 
/*!40000 ALTER TABLE `prices` DISABLE KEYS */; 

INSERT INTO `prices` (`id`, `pricetime`, `price`) 
VALUES 
    (1,'2014-01-01 21:55:00',1.37622000), 
    (2,'2014-01-01 21:56:00',1.37616000), 
    (3,'2014-01-01 21:57:00',1.37616000), 
    (4,'2014-01-01 21:58:00',1.37498000), 
    (5,'2014-01-01 21:59:00',1.37529000), 
    (6,'2014-01-01 22:03:00',1.37518000), 
    (7,'2014-01-01 22:05:00',1.37542000), 
    (8,'2014-01-01 22:06:00',1.37558000), 
    (9,'2014-01-01 22:07:00',1.37560000), 
    (10,'2014-01-01 22:08:00',1.37560000); 

/*!40000 ALTER TABLE `prices` ENABLE KEYS */; 
UNLOCK TABLES; 
+0

원하는 결과는 무엇입니까? – Strawberry

+0

무엇이 p2.pricetime입니다. 각 p1.pricetime에 대해 p2.price = max (p2.price)입니까? – dataphile

답변

0

나는 이것이 당신이 다음 가격을 얻으려면 쿼리이라고 추측하고있다 :

select p.*, 
     (select p2.price 
     from prices p2 
     where p2.id > p.id 
     order by p2.id 
     limit 1 
     ) as nextprice 
from prices p; 

이 최대 변화를 얻으려면 당신을 할 수있다 :

select p.*, 
     (select p2.price 
     from prices p2 
     where p2.id > p.id 
     order by p2.id 
     limit 1 
     ) as nextprice 
from prices p 
order by nextprice - price desc 
limit 1; 

성능을 위해 prices(id, price)에 대한 색인이 필요합니다.

가장 효율적인 방법은 id이 순차적이며 간격이 없다고 가정하는 것입니다. 나는이 질문에 유래가 태그와 상관-하위 쿼리를 제안 물었을 때,

select p.*, pnext.price 
from prices p join 
    prices pnext 
    on p.id = pnext.id - 1 
order by pnext.price - p.price desc 
limit 1; 
0

감사 고든 :이 경우에 자체 조인이 가장 좋습니다. 거기에 대답이 거짓말했습니다. 그래서 여기 간다 :

최대 상승 시간 : 귀하의 의견

SELECT p1.pricetime starttime, min(p4.pricetime) endtime, 
p1.price startingprice, p4.price maxnextprice 
FROM prices p1 inner join prices p4 on p4.id > p1.id 
WHERE p4.price = 
(SELECT max(p3.price) 
FROM prices p2 inner join prices p3 on p3.id > p2.id 
where p1.id = p2.id 
group by p2.pricetime order by max(p3.price) limit 1) 
group by p1.pricetime, p4.price; 

감사합니다.