簡體   English   中英

與另一個表聯接子查詢

[英]JOIN a subquery with another table

在我的MySQL數據庫中,我有兩個表: investments (帶有currency_id和投資date )和currencies (帶有名稱等數據)。

我想為投資表中的每種貨幣選擇最短date ,然后將此結果與currencies合並。

我想象中的查詢可能會更清楚:

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

但是,我得到的只是子查詢結果,沒有連接Currency表中的任何內容。 我究竟做錯了什么?

SELECT子句中,您忘記獲取currencies列的值。 在第一行添加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

但是,您忘記了從貨幣中選擇列,但仍然可能無法提供所需的輸出,因為在子查詢中,您正在選擇所有列,並且僅按currency_id分組。 查詢可能不會運行或未按未添加組功能的所有其余列進行分組,因此您可能會得到意外的結果。 因此,我想建議以下方式

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM