我希望从两个表中检索数据,我需要从第二个表中获取多个值(来自不同日期的价格)。以下工作正常,但我不是一个SQL骑师,我有一个潜在的怀疑,必须有一个比加入第二个表两次更好的方法。有吗?
SELECT A.date, A.symbol, A.Value, B.close, C.close
FROM Potential A
LEFT JOIN Stock_Daily B ON A.symbol = B.symbol
LEFT JOIN Stock_Daily C ON A.symbol = C.symbol
WHERE A.Date = "2015-08-05" AND B.date = "2015-08-05" AND C.date = "2015-08-04"
ORDER BY value DESC LIMIT 20;
提前致谢!
答案 0 :(得分:0)
在B
和C
上使用不同条件进行双重加入就可以了。使用子查询使查询更容易阅读可能更优雅:
SELECT A.date, A.symbol, A.Value, B.close, C.close
FROM Potential A
LEFT JOIN (SELECT close, date
FROM Stock_Daily
WHERE date = "2015-08-05") B ON A.symbol = B.symbol
LEFT JOIN (SELECT close, date
FROM Stock_Daily
WHERE date = "2015-08-05") C ON A.symbol = C.symbol
WHERE A.Date = "2015-08-05"
ORDER BY value DESC LIMIT 20;
但最终,这只是一个品味问题 - 你的查询很好。
答案 1 :(得分:0)
以您执行此操作的方式完成此操作非常方便,但要在评论中进一步扩展,您的查询可能存在问题。由于您在联接表的LEFT JOIN
子句中使用条件逻辑WHERE
,因此它有效地将LEFT JOIN
转换为INNER JOIN
。
如果右侧表格中缺少任何日期而不满足INNER JOIN
,则会给您不正确的结果。
我建议将查询更改为以下内容以避免这种情况:
SELECT A.date, A.symbol, A.Value, B.close, C.close
FROM Potential A
LEFT JOIN Stock_Daily B ON A.symbol = B.symbol AND B.date = "2015-08-05"
LEFT JOIN Stock_Daily C ON A.symbol = C.symbol AND C.date = "2015-08-04"
WHERE A.Date = "2015-08-05"
ORDER BY value DESC LIMIT 20;
答案 2 :(得分:0)
您可以使用case
表达式和group by
:
SELECT
p.date, p.symbol,
min(p.value) value, /* dummy aggregate */
min(CASE WHEN s.Date = p.Date THEN s.close END) Close1,
min(CASE WHEN s.Date = DATE_ADD(p.Date, INTERVAL 1 DAY THEN s.close END) Close2
FROM
Potential p
LEFT OUTER JOIN Stock_Daily s
ON s.symbol = p.symbol AND
(s.date = p.date or s.date = DATE_ADD(p.date, INTERVAL 1 DAY))
GROUP BY p.date, p.symbol
ORDER BY value DESC LIMIT 20;