我有一个相当复杂的查询,其中包括子查询连接中的SQL计数。
问题是Cake的查询构建器返回23的计数,但我知道这是不正确的。所以我调试了它构建的SQL查询,并直接在MySQL中运行它。奇怪的是,Cake生成的原始SQL是正确的,当我运行它时它会返回1,这也是正确的。
我对于将此称为查询构建器的错误犹豫不决,但似乎Cake解释SQL结果的方式是错误的。我不明白这里有什么问题,或者这是怎么回事。
我已经在这里查询了导致问题的基础知识。
查询对象
这是查询构建器生成的内容。 SQL是正确的。
object(Cake\ORM\Query) {
'(help)' => 'This is a Query object, to get the results execute or iterate it.',
'sql' => 'SELECT Orders.order_id AS `Orders__order_id`, all_orders.total AS `Customers__orders_placed`, Customers.id AS `Customers__id`, Customers.email AS `Customers__email`, FROM orders Orders LEFT JOIN (SELECT T.customer_id AS `T__customer_id`, COUNT(*) AS `total` FROM orders T GROUP BY customer_id ) all_orders ON all_orders.T__customer_id = :c0 LEFT JOIN customers Customers ON Customers.id = (Orders.customer_id) WHERE Orders.order_id = :c1',
'params' => [
':c0' => [
'value' => 'Orders.customer_id',
'type' => null,
'placeholder' => 'c0'
],
':c1' => [
'value' => '12345',
'type' => 'string',
'placeholder' => 'c1'
]
],
// ...
Cake生成的SQL(为便于阅读而格式化)
SELECT
Orders.order_id AS `Orders__order_id`,
all_orders.total AS `Customers__orders_placed`,
Customers.id AS `Customers__id`,
Customers.email AS `Customers__email`,
FROM orders Orders
LEFT JOIN (
SELECT T.customer_id AS `T__customer_id`,
COUNT(*) AS `total`
FROM orders T
GROUP BY customer_id
) all_orders ON all_orders.T__customer_id = :c0
LEFT JOIN customers Customers ON Customers.id = (Orders.customer_id)
WHERE Orders.order_id = :c1
查询构建器结果
请注意customer->orders_placed
= 23
object(App\Model\Entity\Order) {
'order_id' => '12345',
'customer' => object(App\Model\Entity\Customer) {
'orders_placed' => '23',
'id' => (int) 34727,
'email' => 'xxxxx@example.com',
'[new]' => false,
'[accessible]' => [
'*' => true
],
'[dirty]' => [],
'[original]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Customers'
},
'[new]' => false,
'[accessible]' => [
'*' => true
],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Orders'
}
如果我自己在MySQL中运行查询
我从Cake的SQL中唯一更改的是填写:c0
和:c1
的参数。
SELECT
Orders.order_id AS `Orders__order_id`,
all_orders.total AS `Customers__orders_placed`,
Customers.id AS `Customers__id`,
Customers.email AS `Customers__email`
FROM orders Orders
LEFT JOIN (
SELECT T.customer_id AS `T__customer_id`,
COUNT(*) AS `total`
FROM orders T
GROUP BY customer_id
) all_orders ON all_orders.T__customer_id = Orders.customer_id
LEFT JOIN customers Customers ON Customers.id = (Orders.customer_id)
WHERE Orders.order_id = 12345
然后当我在MySQL中运行它时,结果是:
Orders__order_id | Customers__orders_placed | Customers__id | Customers__email
-------------------------------------------------------------------------------
12345 | 1 | 34727 | xxxxx@example.com
当我真的复制/粘贴Cake生成的SQL时,计数怎么会有所不同?
Cake版本是3.3.16