如何创建有效的DQL语句,以便在执行简单的LEFT JOIN时匹配我的高效SQL?

时间:2016-06-06 23:10:09

标签: mysql doctrine-orm dql

我可以创建一个简单的SQL,当有一个项目包含请求1且相应的idmodel匹配时,我会返回FS-%,否则会0

但是当我尝试将其写成DQL时,我会以惊人的方式失败。请参阅下面的EXPLAIN结果。

问题:如何编写高效的DQL?

SQL(高效)

select count(*) 
from item 
left join product on item.product_id = product.id 
where item.id=2222 and product.model like "FS-%";

使用说明:

+----+-------------+---------+-------+--------------------+---------+---------+-------+------+-------+
| id | select_type | table   | type  | possible_keys      | key     | key_len | ref   | rows | Extra |
+----+-------------+---------+-------+--------------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | item    | const | PRIMARY,product_id | PRIMARY | 4       | const |    1 |       |
|  1 | SIMPLE      | product | const | PRIMARY            | PRIMARY | 4       | const |    1 |       |
+----+-------------+---------+-------+--------------------+---------+---------+-------+------+-------+

DQL(非效率)

 $this->getEntityManager()
        ->createQueryBuilder()
        ->select('count(i)')
        ->from(Item::class, 'i')
        ->leftJoin(Product::class, 'p')
        ->where('i.id = :id')
        ->andWhere('p.model like :model')
        ->setParameter('id', 2222)
        ->setParameter('model', 'FS-%')
        ->getQuery()->getSingleResult();

结果SQL:

SELECT * FROM item i0_ LEFT JOIN product p1_
        ON (i0_.id = 409264 AND p1_.model LIKE 'FS-%');

使用说明:

+----+-------------+-------+------+---------------+------+---------+------+--------+-------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows   | Extra |
+----+-------------+-------+------+---------------+------+---------+------+--------+-------+
|  1 | SIMPLE      | i0_   | ALL  | NULL          | NULL | NULL    | NULL | 276000 |       |
|  1 | SIMPLE      | p1_   | ALL  | NULL          | NULL | NULL    | NULL |    564 |       |
+----+-------------+-------+------+---------------+------+---------+------+--------+-------+
2 rows in set (0.00 sec)            

注意:我使用https://stackoverflow.com/a/25887143/2883328来帮助我编写DQL。

1 个答案:

答案 0 :(得分:1)

在你的情况下,我会尝试这个查询:

$this->getEntityManager()
        ->createQueryBuilder()
        ->select('count(i)')
        ->from(Item::class, 'i')
        ->leftJoin(Product::class, 'p', 'WITH', 'i.product = p.id')
        ->where('i.id = :id')
        ->andWhere('p.model like :model')
        ->setParameter('id', 2222)
        ->setParameter('model', 'FS-%')
        ->getQuery()->getSingleScalarResult();

i.product中的产品更改为您的媒体资源名称