我有两个数据表,我使用Inner Join语句查询。其中一个表格提取每日公司股票信息,因此每个公司在市场开放的每一天都有一排。另一个表格包含有关公司的定性数据,每个公司只有一行。
我正在尝试提取最新的股票信息,并将其与HTML表格中的定性公司信息配对。我有一切工作,除了它仍然拉动公司的每一行每日信息而不是最新的。
有人可以协助此查询吗?:
$query = "SELECT daily_info.Day,
daily_info.Prev_close,
stocks.Symbol,
stocks.Company,
stocks.Description
FROM daily_info
INNER JOIN stocks ON daily_info.Symbol = stocks.Symbol
ORDER BY daily_info.Day, stocks.Company LIMIT 43
";
Example:
Table 1: Daily_info
Day | Symbol | Company | Prev Close
06/15/14 | CRM | Salesforce | $52.34
06/15/14 | AMZN | Amazon | $342.65
06/16/15 | CRM | Salesforce | $55.24
06/16/14 | AMZN | Amazon | $349.64
Table 2: Stock
Symbol | Company | Description
CRM | Salesforce.com | This is a cloud based CRM company
AMZN | Amazon.com | This is an ecommerce company
Output:
Company | Symbol | Prev Close | Description
Amazon.com | AMZN | $349.64 | This is an ecommerce company
Salesforce.com | CRM | $55.24 | This is a cloud based CRM company
答案 0 :(得分:0)
我不认为MySQL支持LAG功能,所以你需要做一个子查询来获取每个Symbol的最后日期,然后INNER加入该结果。这样的事情应该有效:
$query = "
SELECT l.Company, l.Symbol, l.Prev_Close, r2.Description
FROM Daily_info as l
INNER JOIN
(SELECT Symbol, MAX(Prev_close) as last_date FROM Daily_info GROUP BY Symbol) AS r
ON (l.Symbol=r.Symbol AND l.Prev_close=r.last_date)
INNER JOIN Stock as r2
ON (l.Symbol=r2.Symbol)
";