mysql - 使用 MySQL 用户定义变量和 CakePHP3 查询选择
问题描述
这是我需要的一个例子:
SELECT
@earnings := (`house_rent`+`conveyance`+`medical`+`dearness`+`others_allowances`) AS earnings ,
@deductions := (`income_tax`+`pro_tax`+`emp_state_insu`+`absence_fine`+`others_deductions`) AS deductions,
@earnings - @deductions AS net_salary
FROM
salary
就我而言,我需要将 aSUM(Table.total)
作为单独的salesTotal
列返回,并在内部重用@salesTotal/@salesQuantity
.
这是我尝试过的:
1.
$query->select([
$query->newExpr([
'@salesTotal := ',
$query->func()->sum('Table.total')
]),
]);
这会产生@salesTotal := AND SUM(Table.total)
2.
$query->select([
$query->newExpr([
'@salesTotal := ' . $query->func()->sum('Table.total')
]),
]);
导致警告 (4096):Cake\Database\Expression\FunctionExpression 类的对象无法转换为字符串
3.
$query->select([
$query->newExpr([
'@salesTotal := SUM(Table.total)'
]),
]);
收到警告 (2): array_combine () : 两个参数应该有相同数量的元素CORE/src/ORM/ResultSet.php,第 527 行。这也不是一个好的解决方案。
解决方案
由于您没有绑定任何值,因此您可以简单地按字面意思编写子句,而无需任何复杂性。像这样:
$query
->select(array(
'@earnings := (`house_rent`+`conveyance`+`medical`+`dearness`+`others_allowances`) AS earnings',
'@deductions := (`income_tax`+`pro_tax`+`emp_state_insu`+`absence_fine`+`others_deductions`) AS deductions',
'@earnings - @deductions AS net_salary',
))
->from('salary')
;
我没有一个填充表来测试它并确定它确实返回了你想要的,但它确实使用 CakePHP 为这个结构返回了一个空数组(而不是抛出异常):
CREATE TABLE salary (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
house_rent INT DEFAULT 0,
conveyance INT DEFAULT 0,
medical INT DEFAULT 0,
dearness INT DEFAULT 0,
others_allowances INT DEFAULT 0,
income_tax INT DEFAULT 0,
pro_tax INT DEFAULT 0,
emp_state_insu INT DEFAULT 0,
absence_fine INT DEFAULT 0,
others_deductions INT DEFAULT 0
);
推荐阅读
- javascript - 使用 JS 和 SVG 动态添加和删除类时遇到问题
- node.js - Rackspace 云上传时间过长?
- javascript - 如何动态更新 req.write('{ "upc":"make-this-dynamic"}') 的字符串中的值?
- python-3.x - Conda 似乎加载了 Geopandas,但未添加到 IBM Watson Studio Notebook Python 3.6
- matlab - 如何在 Matlab 中显示 yaxis 上的完整数字?
- spinnaker - 为什么 Spinnaker 需要在已知名称空间的情况下列出名称空间?
- anaconda - conda:为什么我不能在一个环境中安装 pkgs,而我可以在另一个环境中安装?
- ruby-on-rails - 在没有多个后续查询的情况下设置集合缓存键
- c++ - 带有成员 (operator[]) 函数的invoke_result
- azure - 从跨项目的 AzDO 管道构建统计信息创建 Power BI 仪表板