原则从第二个表中选择与第一个表匹配的最后一个记录

时间:2018-11-20 14:25:33

标签: mysql doctrine-orm doctrine

enter image description here

我有两个表,第一个表与表单有关,第二个表与顾问相关。每个顾问都可以为表单添加注释。 我尝试选择两个表的某些列。这是我的作品,我的结果中有第二个表的最后一个主题( adviser表)。但是我需要第二个表的第一个主题( adviser表)。

#DQL
SELECT
    f.name,
    f.title,
    f.conditionResultFinal,
    f.conditionResult,
    f.formCode,
    f.dateInsert,
    f.id,
    (a.idFormRequestProject),
    a.subject as subjectAdvisor
FROM AdminBundle:FormRequestProject f
JOIN AdminBundle:Advisor a
WHERE a.idFormRequestProject = f.id
    AND (f.conditionResultFinal = 0 OR f.conditionResult = 0)
    AND f.displayStatus = 1
GROUP BY f.id
ORDER by a.id,f.id DESC

1 个答案:

答案 0 :(得分:0)

最后,我解决了这个问题。我删除了 GROUP By 。并添加了新的其中 ...

SELECT f.name,f.title,f.conditionResultFinal,
f.conditionResult ,
f.formCode,f.dateInsert ,
f.id,(a.idFormRequestProject),
a.subject as subjectAdvisor 
FROM AdminBundle:FormRequestProject f  
Left JOIN AdminBundle:Advisor a WHERE  f.id = a.idFormRequestProject AND a.id = 
(SELECT  Max (aa.id) FROM AdminBundle:Advisor aa WHERE a.idFormRequestProject = 
aa.idFormRequestProject ORDER by aa.id ASC )  AND 
(f.conditionResultFinal = 0 OR f.conditionResult = 0 ) AND  f.displayStatus =1   
ORDER by f.id DESC