我有一个更长,更复杂的代码,我希望从表中获得最新的条目,但我收到最旧的一个。我尝试过:MIN(date), Max(date) desc
和asc
。它不起作用。我的代码是否需要特殊的解决方案?
SELECT stock_id,
stocks.name,
DATE_FORMAT(date, '%Y-%m-%d %H:%i:%s') AS date,
price, pxchange,
CONCAT(round(pxpct*100, 4), '%') AS pxpct,
stocks.stockmarket,
stockmarkets.id
FROM (SELECT CASE WHEN stock_id <> @pxticker THEN @pxclose := NULL END,
p.*,
(price - @pxclose) AS pxchange,
(price - @pxclose) / @pxclose AS pxpct,
(@pxclose := price),
(@pxticker := stock_id)
FROM quotations p CROSS JOIN
(SELECT @pxclose := NULL, @pxticker := stock_id
FROM quotations
ORDER BY stock_id, date
LIMIT 1) AS a
ORDER BY stock_id, date) AS b
LEFT JOIN stocks ON stock_id = stocks.id
LEFT JOIN stockmarkets ON stockmarkets.id = stocks.stockmarket
WHERE stocks.stockmarket = (SELECT id FROM stockmarkets WHERE short ='".$q."')
GROUP BY stock_id
ORDER BY stock_id, MIN(date) ASC
我正在思考和工作几个小时,经过尝试和尝试。但似乎没有任何帮助。
感谢任何可以提供帮助的人。如果我的吸收速度很慢,我不会感到惊讶。
- 编辑 - 示例
我得到但不想要的。
4 Facebook, Inc. 2014-02-24 14:43:49 7 NULL NULL 1 1
5 Tesla Motors, Inc. 2014-02-24 14:59:28 7 NULL NULL 1 1
我想要的(样本值,日期 - 时间戳 - 很重要)。
4 Facebook, Inc. 2014-03-10 22:33:39 50 NULL NULL 1 1
5 Tesla Motors, Inc. 2014-03-10 22:52:28 20 NULL NULL 1 1
根据上面的语法,我想得到我连接到纳斯达克的每一只股票的最新报价(在这个例子中)。但我总是得到我在表格'引用'中插入的最早的第一个引文。
EDIT
编辑2 - 代码
SELECT stock_id,
stocks.name,
DATE_FORMAT(date, '%Y-%m-%d %H:%i:%s') AS date,
price, pxchange,
CONCAT(round(pxpct*100, 4), '%') AS pxpct,
stocks.stockmarket,
stockmarkets.id
FROM (SELECT CASE WHEN stock_id <> @pxticker THEN @pxclose := NULL END,
p.*,
(price - @pxclose) AS pxchange,
(price - @pxclose) / @pxclose AS pxpct,
(@pxclose := price),
(@pxticker := stock_id)
FROM quotations p CROSS JOIN
(SELECT @pxclose := NULL, @pxticker := stock_id
FROM quotations
ORDER BY date, stock_id
LIMIT 1) AS a
ORDER BY date, stock_id) AS b
LEFT JOIN stocks ON stock_id = stocks.id
LEFT JOIN stockmarkets ON stockmarkets.id = stocks.stockmarket
WHERE stocks.stockmarket = (SELECT id FROM stockmarkets WHERE short ='NASDAQ')
GROUP BY stock_id
ORDER BY date, stock_id
这是一个小提琴:http://www.sqlfiddle.com/#!2/ff809/44 不完全相同的数据,但我正在使用的代码。还有同样的问题:如何获得最新的条目?
EDIT - 有关结构信息的屏幕截图 以下是有关所用表格的内容和结构的屏幕截图。也许有帮助。
答案 0 :(得分:1)
如果您想要最早的记录,那么order by子句应首先具有日期。 更改以下
ORDER BY stock_id, date DESC
与
ORDER BY date DESC, stock_id