简体   繁体   中英

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

I would like to select the minimum date for each currency inside investments table and then join this result with 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. What am I doing wrong?

In SELECT clause, you forget to get currencies columns' values. Add currencies.* at the first line.

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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM