mysql与子查询连接

时间:2017-04-06 07:33:25

标签: mysql join subquery

这是我的架构:

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)

我添加了列打开和低,我想填写表中的数据。

这些值打开/关闭以每天为参考。(因此每天的相对最大/最小ID应该给我正确的值)。所以我的第一个见解是获取日期列表,然后加入表:

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

但我被卡住了,因为我无法获得最大/最小ID或第一个/最后一个值。感谢

2 个答案:

答案 0 :(得分:1)

您将从下面的查询中获得明智的最小和最大ID

 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")

但其他要求尚不清楚。

答案 1 :(得分: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