2017-01-02 89 views
0

我有一個與MySQL通常執行的查詢:語義錯誤,Symfony的DQL

SELECT * 
FROM td_user u 
JOIN td_ranking ranking ON ranking.user_id = u.id 
JOIN (
SELECT x.user_id, 
MAX(x.id) AS default_id 
FROM td_ranking x 
GROUP BY x.user_id 
) y 
ON y.user_id = ranking.user_id 
AND y.default_id = ranking.id 

我試圖改變它在DQL的運行它的Symfony:

$query = $this->_em->createQuery(' 
    SELECT u.*,ranking.* 
    FROM UserBundle:User u 
    JOIN UserBundle:Ranking ranking 
    WITH ranking.user_id = u.id 
    JOIN (
    SELECT x.user_id, MAX(x.id) AS default_id 
    FROM UserBundle:Ranking x 
    GROUP BY x.user_id 
) y 
    ON y.user_id = ranking.user_id 
    AND y.default_id = ranking.id' 
); 
$results = $query->getResult(); 

我有這樣的錯誤:

[語義錯誤] 0行,列113 '附近(SELECT x.user_id,':錯誤:類 '(' 沒有定義

你有什麼想法嗎?謝謝!

+1

您不必爲排名實體USER_ID財產。 –

+0

哦,是的......但如何做到這一點?我嘗試這一點,但結果是一樣的:「 選擇U *,*排名從 UserBundle:用戶U JOIN UserBundle:排名排名 WITH ranking.user_id = u.id JOIN( SELECT x.user ,MAX(x.id)AS default_id FROM UserBundle:Ranking x GROUP BY x.user)y ON y.user = ranking.user AND y.default_id = ranking.id「 – Tom59

+0

事實上,我有一個OneToMany用戶與排名的關係。許多排名可以鏈接到用戶。在我的要求中,我想獲取每個用戶的最後排名......您有想法嗎? – Tom59

回答

2

使用本地查詢

$rsm = new ResultSetMapping(); 
$sql = " 
    SELECT * 
FROM td_user u 
JOIN td_ranking ranking ON ranking.user_id = u.id 
JOIN (
SELECT x.user_id, 
MAX(x.id) AS default_id 
FROM td_ranking x 
GROUP BY x.user_id 
) y 
ON y.user_id = ranking.user_id 
AND y.default_id = ranking.id 
"; 

$result = $this->getEntityManager()->createNativeQuery($sql, $rsm)->getResult(); 
+0

謝謝!但是,我有這樣的錯誤:無法找到名稱爲「 SELECT * FROM ütd_user JOIN 排名td_ranking ON ranking.user_id = u.id JOIN(SELECT x.user_id, MAX(x.id一個名爲原生查詢)AS default_id FROM td_ranking x GROUP BY x.user_id)y ON y.user_id = ranking.user_id AND y.default_id = ranking.id「 – Tom59

+1

請使用更新的ans –

+1

@ Tom59請使用更新的ans。 –