我一直在尝试将以下原始sql转移到dql中,我无法做四个小时,你能帮助我吗? 此查询在数据库中查找重复的哈希值,并为我提供订单的ID
SELECT h.order_id
FROM `Hash` h
INNER JOIN (SELECT `order_id`,hash
FROM `Hash`
GROUP BY `hash`
HAVING COUNT(*) > 1
) dt ON h.hash=dt.hash ;
和我的dql现在:
SELECT h FROM PaymentBundle:Hash h
JOIN
(SELECT h1.order, h1.hash FROM PaymentBundle:Hash h1 GROUP BY h1.hash HAVING COUNT(h1) > 1)
dt WITH h.hash = dt.hash
但是h1.order
给出了语法错误,以及其他所有内容:
[Semantical Error] line 0, col 40 near '(SELECT h1.hash': Error: Class '(' is not defined.
我尝试将其作为子查询:
$subDql = 'SELECT h1 FROM PaymentBundle:Hash h1 GROUP BY h1.hash HAVING COUNT(h1) > 1';
$subQuery = $this->getEntityManager()
->createQuery($subDql);
$dql = 'SELECT h FROM PaymentBundle:Hash h JOIN ('.$subQuery->getDQL().') dt ON h.hash = dt.hash';
$query = $this->getEntityManager()
->createQuery($dql);
return $query->getResult();
它给了我:
[学说\ ORM \查询\ QueryException]
[语义错误]第0行,第40列附近'(SELECT h1 FROM':错误:类 '('未定义。[学说\ ORM \查询\ QueryException]
SELECT h FROM PaymentBundle:Hash h JOIN(SELECT h1 FROM PaymentBundle:Hash h1 GROUP BY h1.hash HAVING COUNT(h1)> 1)dt ON h.hash = dt.hash
答案 0 :(得分:1)
我的解决方案:
$rsm = new ResultSetMappingBuilder($this->getEntityManager());
$rsm->addRootEntityFromClassMetadata('PaymentBundle:Hash', 'h');
$qb = $this->getEntityManager()->createNativeQuery("
SELECT h.id, h.order_id
FROM `Hash` as h
INNER JOIN (SELECT `order_id`,hash
FROM `Hash`
GROUP BY `hash`
HAVING COUNT(*) > 1
) dt ON h.hash = dt.hash
", $rsm);
return $qb->getResult();