我正在尝试使用cakePHP 3.5中的子查询来构建查询,但是它与预期不符,请在下面找到详细信息并帮助我解决它。
SQL:-
$sql = '
SELECT
t1.id, t1.code, t1.description, t1.customer_id, t1.delivery_date
(
SELECT SUM(t2.quantity) AS completed
FROM table2 AS t2
WHERE t2.customer_id = t1.customer_id
AND t2.delivery_date = t1.delivery_date
) AS completed
FROM table1 AS t1
';
这是我要使用CakePHP ORM构建的查询
CakePHP查询:-
我已经尝试过以下代码来实现查询
$data = $this->Table1->query->select([
't1.id',
't1.code',
't1.description',
't1.customer_id',
't1.delivery_location_id',
'completed' => $this->Table2->find()->select([
'completed' => 'SUM(Table2.quantity)'
])->where([
'Table2.customer_id' => 'Table1.customer_id',
'Table2.delivery_location_id' => 'Table1.delivery_location_id'
])
]);
实际输出:-
这是我实际使用的CakePHP ORM,您可以在子查询的WHERE条件下看到它为0。
SELECT
Table1.id AS `Table1__id`,
Table1.code AS `Table1__code`,
Table1.description AS `Table1__description`,
Table1.customer_id AS `Table1__customer_id`,
Table1.delivery_location_id AS `Table1__delivery_location_id`,
(
SELECT
sum(
Table2.quantity
) AS `completed`
FROM
table2 Table2
WHERE (
Table2.customer_id = 0
AND Table2.delivery_location_id = 0
)
) AS `completed`,
FROM
table1 Table1
LIMIT
10 OFFSET 0
预期输出:-
我期望输出如下。
SELECT
Table1.id AS `Table1__id`,
Table1.code AS `Table1__code`,
Table1.description AS `Table1__description`,
Table1.customer_id AS `Table1__customer_id`,
Table1.delivery_location_id AS `Table1__delivery_location_id`,
(
SELECT
sum(
Table2.quantity
) AS `completed`
FROM
table2 Table2
WHERE (
Table2.customer_id = Table1.customer_id
AND Table2.delivery_location_id = Table1.delivery_location_id
)
) AS `completed`,
FROM
table1 Table1
LIMIT
10 OFFSET 0