简体   繁体   English

SF2-教义DQL-选择几列

[英]SF2 - Doctrine DQL - Select several columns

I have a table Item with the following columns: 我有一个包含以下各列的表Item:

  • Id ID
  • Category 类别
  • value
  • date 日期

I build a SQL request which returns all the lines with the latest date for each category: 我建立一个SQL请求,该请求返回每个类别的最新日期的所有行:

SELECT *
FROM item i
WHERE (i.category, i.date) IN (SELECT category, MAX(date)
                               FROM item
                               GROUP BY category)

This works fine and returns what I need. 这工作正常,并返回我需要的。

I work with Symfony2 and Doctrine, so I would prefer to use DQL (or even better: the QueryBuilder) instead of NativeSQL. 我使用Symfony2和Doctrine,所以我更喜欢使用DQL(甚至更好:QueryBuilder)而不是NativeSQL。

So here is my DQL request : 所以这是我的DQL请求:

SELECT i
FROM MyBundle:Item i
WHERE (i.category, i.date) IN (SELECT i2.category, MAX(i2.date) 
                               FROM MyBundle:Item i2
                               GROUP BY i2.category
                               )

Which gives me the error: 这给了我错误:

QueryException: [Syntax Error] line 0, col 103: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got ','

If I remove the first couple of parenthesis, I get : 如果删除括号的前几对,则会得到:

QueryException: [Syntax Error] line 0, col 102: Error: Expected =, <, <=, <>, >, >=, !=, got ','

I thought there was a problem with the WHERE so I tried the following just to see what would happen: 我以为WHERE存在问题,因此我尝试了以下操作,以了解会发生什么:

SELECT i
FROM MyBundle:Item i
WHERE i IN (SELECT i2.category, MAX(i2.date) 
            FROM MyBundle:Item i2
            GROUP BY i2.category
            )

I get: 我得到:

QueryException: [Syntax Error] line 0, col 116: Error: Expected Doctrine\ORM\Query\Lexer::T_FROM, got ','  

But in the doctrine doc, there is an example with several columns after the SELECT, using this same syntax! 但是在学说文档中, 有一个使用相同语法在SELECT之后有几列的示例

Do you have any idea where does my problem come from? 您知道我的问题来自哪里吗? Thank you! 谢谢! Regards, 问候,

You will need to separate the query's conditional statements; 您将需要分离查询的条件语句。 This is because DQL is unable to parse the comma separated field names (i.category, i.date) . 这是因为DQL无法解析以逗号分隔的字段名称(i.category, i.date)

SELECT 
  i 
FROM 
  MyBundle:Item i 
WHERE
  i.category IN ( (SELECT i2.category FROM MyBundle:Item i2 GROUP BY i2.specy) )
AND
  i.date IN ( (SELECT MAX(i2.date) FROM MyBundle:Item i2 GROUP BY i2.specy) )

I would also recommend using parentheses () to wrap any sub queries. 我还建议使用括号()来包装所有子查询。

You could use exists : 您可以使用exists

SELECT 
  i 
FROM 
  MyBundle:Item i 
WHERE
  EXISTS (
    SELECT i2 
    FROM MyBundle:Item i2
    WHERE i2.category = i.category
    GROUP BY i2.category
    HAVING MAX(i2.date) = i.date
  )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM