2014-09-23 52 views
1

我有一個查詢從5個表中檢索信息。它們之間的關係顯示在附圖中。我已經創建了一個查詢來做到這一點,迄今爲止這麼好。問題是每個用戶在「PROFISSIONAL_PORCENTAGEM」表中可以有一個或多個條目。我的查詢是檢索所有他們。我想要基於日期字段「PROFISSIONAL_PORCENTAGEM_DATA」的最後一個字段。我對這個問題進行了研究,當我們僅使用一個表時,「檢索每個ID的最近值」的解決方案是相同的,請參閱MySQL - Selecting the most recent post by each of the 10 most recent authors這裏的示例。但在這種情況下,我有5張桌子。我不知道該怎麼做。任何想法將不勝感激。Mysql - 最近爲每個ID輸入

SELECT 
    PP.PROFISSIONAL_PORCENTAGEM_Pk, 
    UST.USER_NAME, 
    ADDR.ADDRESS_NOME, 
    ADDR.ADDRESS_ATIVO, 
    PA.PROFESSIONAL_ADDRSS_PK, 
    PP.PROFISSIONAL_PORCENTAGEM_PORCENT, 
    PP.PROFISSIONAL_PORCENTAGEM_FK_CLINICA, 
    PP.PROFISSIONAL_PORCENTAGEM_DATA 

FROM 
    profissional_porcentagem AS PP 
    RIGHT JOIN professional_addrss AS PA 
    ON(PP.PROFISSIONAL_PORCENTAGEM_FK_CLINICA=PA.PROFESSIONAL_ADDRSS_PK) 

    INNER JOIN address ADDR 
    ON(PA.PROFESSIONAL_ADDRSS_FKADDRSS=ADDR.ADDRESS_Pk) 

    INNER JOIN professional PF 
    ON(PA.PROFESSIONAL_ADDRSS_FKPROFESSIONAL=PF.PROFESSIONAL_Pk) 

    INNER JOIN usert AS UST 
    ON(PF.PROFESSIONAL_FKUSER=UST.USER_Pk) 

WHERE UST.USER_Pk=3 
AND ADDR.ADDRESS_ATIVO=1; 

對不起,我需要10個聲望來附加圖像! 這是圖像鏈接http://imgur.com/ZP3OdeX

+0

你啓發應該可以將圖像上傳到[imgur](http://www.imgur.com)並提供鏈接。 – Kermit 2014-09-23 14:56:08

+0

你可以嘗試添加用戶有最大(PROFISSIONAL_PORCENTAGEM_DATA),不知道,只是快速回答 – gorgi93 2014-09-23 15:03:10

+1

謝謝克米特。我確實知道這種可能性。現在你可以看到數據庫圖像。 – zwitterion 2014-09-23 15:03:32

回答

1

那麼,最後我找到了解決方案。 只需將此代碼添加到SQL查詢的末尾:

AND PP.PROFISSIONAL_PORCENTAGEM_Pk = (
SELECT t2.PROFISSIONAL_PORCENTAGEM_Pk FROM profissional_porcentagem as t2 
    where t2.PROFISSIONAL_PORCENTAGEM_FK_CLINICA = PP.PROFISSIONAL_PORCENTAGEM_FK_CLINICA 
    order by t2.PROFISSIONAL_PORCENTAGEM_Pk desc limit 1 
) 

然後我們要去有這樣整個查詢:

SELECT 
PP.PROFISSIONAL_PORCENTAGEM_Pk, 
UST.USER_NAME, 
ADDR.ADDRESS_NOME, 
ADDR.ADDRESS_ATIVO, 
PA.PROFESSIONAL_ADDRSS_PK, 
PP.PROFISSIONAL_PORCENTAGEM_PORCENT, 
PP.PROFISSIONAL_PORCENTAGEM_FK_CLINICA, 
PP.PROFISSIONAL_PORCENTAGEM_DATA 

FROM 
profissional_porcentagem AS PP 
RIGHT JOIN professional_addrss AS PA 
    ON(PP.PROFISSIONAL_PORCENTAGEM_FK_CLINICA=PA.PROFESSIONAL_ADDRSS_PK) 

INNER JOIN address ADDR 
    ON(PA.PROFESSIONAL_ADDRSS_FKADDRSS=ADDR.ADDRESS_Pk) 

INNER JOIN professional PF 
    ON(PA.PROFESSIONAL_ADDRSS_FKPROFESSIONAL=PF.PROFESSIONAL_Pk) 

INNER JOIN usert AS UST 
    ON(PF.PROFESSIONAL_FKUSER=UST.USER_Pk) 

WHERE UST.USER_Pk=3 
AND ADDR.ADDRESS_ATIVO=1 

AND PP.PROFISSIONAL_PORCENTAGEM_Pk = (
SELECT t2.PROFISSIONAL_PORCENTAGEM_Pk FROM profissional_porcentagem as t2 
    where t2.PROFISSIONAL_PORCENTAGEM_FK_CLINICA = PP.PROFISSIONAL_PORCENTAGEM_FK_CLINICA 
    order by t2.PROFISSIONAL_PORCENTAGEM_Pk desc limit 1 
); 

注:我被這個帖子Select row with most recent date per user