gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:49:34 25 4
gpt4 key购买 nike

我可以制作一个简单的 SQL,当存在具有请求的 id 和与 FS 匹配的相应 model 的项目时返回 1 -%,否则为 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。

最佳答案

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

$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 中的产品更改为您的属性名称

关于mysql - 在执行简单的 LEFT JOIN 时,如何创建高效的 DQL 语句以匹配高效的 SQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37668166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com