簡體   English   中英

mysql相關子查詢:選擇field1,其中max(field2)

[英]mysql correlated subquery : select field1 where 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 = max(p2.price)?

-獲得最高價格的時間

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

對於數百萬個行表,這是一種極其低效的方式,我相信您可以在MSSQL中執行以下操作:

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;

我猜這是您想要獲得下一個價格的查詢:

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;

謝謝戈登,當我問這個問題時stackoverflow建議將相關子查詢作為標簽。 其中撒謊了答案。 因此,這里去:

最大增加時間:

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;

感謝您的輸入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM