[英]JOIN a subquery with another table
In my MySQL database I have two tables: investments
(with a currency_id
and the date
of investment) and currencies
(with data like name, etc). 在我的MySQL数据库中,我有两个表: investments
(带有currency_id
和投资date
)和currencies
(带有名称等数据)。
I would like to select the minimum date
for each currency inside investments table and then join this result with currencies
. 我想为投资表中的每种货币选择最短date
,然后将此结果与currencies
合并。
The query I imagined would work may make this clearer: 我想象中的查询可能会更清楚:
SELECT T.currency_id, T.mindate
FROM (
SELECT * , MIN( DATE ) AS mindate
FROM investments
GROUP BY investments.currency_id
ORDER BY mindate ASC
) AS T
JOIN currencies ON T.currency_id =
currencies.currency_id
However, all I get is the subquery result, and nothing from currencies table is joined. 但是,我得到的只是子查询结果,没有连接Currency表中的任何内容。 What am I doing wrong? 我究竟做错了什么?
In SELECT
clause, you forget to get currencies
columns' values. 在SELECT
子句中,您忘记获取currencies
列的值。 Add currencies.*
at the first line. 在第一行添加currencies.*
。
SELECT T.currency_id, T.mindate, currencies.*
FROM (
SELECT * , MIN( DATE ) AS mindate
FROM investments
GROUP BY investments.currency_id
ORDER BY mindate ASC
) AS T
JOIN currencies ON T.currency_id =
currencies.currency_id
However you forgot to select the column[s] from currencies but still it would may not give you the desired output because in the subquery you are selecting all the columns and grouping by only currency_id
. 但是,您忘记了从货币中选择列,但仍然可能无法提供所需的输出,因为在子查询中,您正在选择所有列,并且仅按currency_id
分组。 the query may not run or group by all the rest of columns where group function is not added so you may get unexpected results. 查询可能不会运行或未按未添加组功能的所有其余列进行分组,因此您可能会得到意外的结果。 So, I would like to suggest the following way instead 因此,我想建议以下方式
SELECT T.currency_id, T.mindate, u.currency_name
FROM (
SELECT currency_id, MIN(DATE) AS mindate
FROM investments
GROUP BY investments.currency_id) AS T
JOIN currencies u ON u.currency_id = t.currency_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.