2017-04-06 75 views
0

這是我的架構:MySQL的加入與子查詢

mysql> describe stocks; 
+-----------+-------------+------+-----+---------+----------------+ 
| Field  | Type  | Null | Key | Default | Extra   | 
+-----------+-------------+------+-----+---------+----------------+ 
| id  | int(11)  | NO | PRI | NULL | auto_increment | 
| symbol | varchar(32) | NO |  | NULL |    | 
| date  | datetime | NO |  | NULL |    | 
| value  | float(10,3) | NO |  | NULL |    | 
| contracts | int(8)  | NO |  | NULL |    | 
| open  | float(10,3) | NO |  | NULL |    | 
| close  | float(10,3) | NO |  | NULL |    | 
| high  | float(10,3) | NO |  | NULL |    | 
| low  | float(10,3) | NO |  | NULL |    | 
+-----------+-------------+------+-----+---------+----------------+ 
9 rows in set (0.03 sec) 

我加列開低,我想用表裏面的數據來填充。

這些值打開/關閉是每天參考的。(所以每天的相對最大/最小值應該給我正確的值)。所以我的第一個觀點是獲取日期的列表,然後離開攜手同臺:

SELECT DISTINCT(DATE(date)) as date FROM stocks 

,但我堅持,因爲我不能得到的最大/最小ID或第一/最後一個值。由於

回答

1

您將獲得一天明智的最小值和最大值IDS從下面查詢

SELECT DATE_FORMAT(date, "%d/%m/%Y"),min(id) as min_id,max(id) as max_id FROM stocks group by DATE_FORMAT(date, "%d/%m/%Y") 

但是其他的要求是不明確的。

+0

感謝您的幫助,這是我需要用'value'列的值替換min_id,max_id然後插入列高,低的第一步 – egariM

0

解決!

mysql> UPDATE stocks s JOIN 
    -> (SELECT k.date, k.value as v1, y.value as v2 FROM (SELECT x.date, x.min_id, x.max_id, stocks.value FROM (SELECT DATE(date) as date,min(id) as min_id,max(id) as max_id FROM stocks group by DATE(date)) AS x LEFT JOIN stocks ON x.min_id = stocks.id) AS k LEFT JOIN stocks y ON k.max_id = y.id) sd 
    -> ON DATE(s.date) = sd.date 
    -> SET s.open = sd.v1, s.close = sd.v2; 
Query OK, 995872 rows affected (1 min 50.38 sec) 
Rows matched: 995872 Changed: 995872 Warnings: 0