DQL Doctrine查询翻译

时间:2013-04-29 19:28:13

标签: symfony doctrine-orm doctrine greatest-n-per-group dql

我有我的分数表,我有1个用户的多个分数。我要做的是为每个用户选择所有最高分。

我正试图在Doctrine DQL中完成任务:

        SELECT * FROM scores s1
        LEFT OUTER JOIN scores s2 ON
          s1.user_id = s2.user_id
          AND ((s1.score < s2.score) OR (s1.score = s2.score AND s1.date_added < s2.date_added))
        WHERE s2.score IS NULL
        ORDER BY s1.score DESC
        LIMIT 10

我目前的状态是:

    $rowQuery = $this->getEntityManager()->createQuery('
        SELECT s1 FROM \Digital\ApplicationBundle\Entity\ChallengeScore s1
            LEFT OUTER JOIN \Digital\ApplicationBundle\Entity\ChallengeScore s2
        ON (
            s1.user = s2.user
            AND
            (s1.score < s2.score OR (s1.score = s2.score AND s1.date_added < s2.date_added))
        )
        WHERE s2.score IS NULL
        AND s1.date_added BETWEEN :monday AND :sunday
        ORDER BY s1.score DESC
    ');


    $rowQuery->setParameter('monday', $startDate->format('Y-m-d'))
             ->setParameter('sunday', $endDate->format('Y-m-d'));
    $rowQuery->setMaxResults($limit);

    return $rowQuery->getResult();

我收到以下错误:

[Syntax Error] line 0, col 188: Error: Expected Literal, got '�'

我做错了什么?

2 个答案:

答案 0 :(得分:0)

尝试在命名空间中添加两个反斜杠..例如:

$rowQuery = $this->getEntityManager()->createQuery('
    SELECT s1 FROM \\Digital\\ApplicationBundle\\Entity\\ChallengeScore s1
    LEFT OUTER JOIN \\Digital\\ApplicationBundle\\Entity\\ChallengeScore s2 ...

如果这个doe不起作用,请尝试以小部分进行查询,以找出问题所在。

答案 1 :(得分:0)

这应该在DQL中工作,如果您已经为您的实体定义了任何映射,并且仍然希望加入具有公共属性的2个实体,您必须使用ON部分处理WITH部分句柄。SELECT s1 FROM \Digital\ApplicationBundle\Entity\ChallengeScore s1 LEFT OUTER JOIN \Digital\ApplicationBundle\Entity\ChallengeScore s2 WITH s1.user = s2.user AND CASE WHEN s1.score = s2.score THEN s1.date_added < s2.date_added ELSE s1.score < s2.score END WHERE s2.score IS NULL AND s1.date_added BETWEEN :monday AND :sunday ORDER BY s1.score DESC 子句

SELECT s1 
FROM \Digital\ApplicationBundle\Entity\ChallengeScore s1
    LEFT OUTER JOIN \Digital\ApplicationBundle\Entity\ChallengeScore s2
    WITH s1.user = s2.user
    AND (
        s1.score < s2.score OR (s1.score = s2.score AND s1.date_added < s2.date_added)
    )
WHERE s2.score IS NULL
AND s1.date_added BETWEEN :monday AND :sunday
ORDER BY s1.score DESC

OR

private void SetConnection()
{
   sql_con = new SQLiteConnection("DataSource=kyriosDB.db;Version=3;New=False;Compress=True;");
}


public void ExecuteQuery(string txtQuery)
{
    SetConnection();
    sql_con.Open();
    sql_cmd = sql_con.CreateCommand();
    sql_cmd.CommandText = txtQuery;
    sql_cmd.ExecuteNonQuery();
    sql_con.Close();
}