我有一个查询从5个表中检索信息。它们之间的关系如附图所示。我创建了一个查询来做到这一点,到目前为止一直很好。问题是每个用户在“PROFISSIONAL_PORCENTAGEM”表中可以有1个或多个条目。我的查询是检索所有这些。我希望最后一个基于日期字段“PROFISSIONAL_PORCENTAGEM_DATA”。我已经对这个问题进行了研究,当我们只使用一个表时,“检索每个id的最新内容”的解决方案是相同的,请参阅此处的示例MySQL - Selecting the most recent post by each of the 10 most recent authors。但在这种情况下,我有5个表。我不知道该怎么做。任何想法都将不胜感激。
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 :(得分: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