如果有人帮我,谢谢你的预付款。
以下是根据不同参数筛选某些客户的查询。在最后一个筛选器中,我需要根据查询中的计算字段对客户进行筛选,当我尝试在where子句中使用计算字段时,它会显示未知字段的错误,我应该怎么做?
$sql = <<<SQL
SELECT c.*, t.name as town_name, r.name as region_name, IFNULL((
select sum(p.remaining)
from payments p
left join sales s
on s.payment_id = p.id
where s.customer_id = c.id and s.status = 1
), 0) as credit_sales,
(
IFNULL((
SELECT sum(cl.amount)
FROM customer_ledgers cl
WHERE cl.customer_id = c.id and cl.status = 1 and cl.type = 1
), 0)
-
IFNULL((
SELECT sum(amount)
FROM customer_ledgers
WHERE customer_id = c.id and status=1 and type = 2
), 0)
) as balancex, (
IFNULL( (
SELECT `amount`
FROM `customer_ledgers`
WHERE customer_id = c.id and status = 1
ORDER BY `date` DESC
LIMIT 1
), 0)
) as last_amount
from customers c
left join regions r
on r.id = c.region_id
left join towns t
on t.id = c.town_id
sql语句
# we need where?
$sql .= 'WHERE c.status = 1';
if (isset($params['CustomerSearch'])) {
$sql .= " and ";
}
# add where statements to the query
if (isset($params['CustomerSearch'])) {
$isname = isset($params['CustomerSearch']['name']);
$istown = isset($params['CustomerSearch']['region_name']);
$isregion = isset($params['CustomerSearch']['town_name']);
$isbalance = isset($params['CustomerSearch']['balancex']);
if (isset($params['CustomerSearch']['name'])) {
$this->name = trim($params['CustomerSearch']['name']);
$sql .= " c.name like '%{$this->name}%'";
}
if (isset($params['CustomerSearch']['region_name']) && $params['CustomerSearch']['region_name'] !== '') {
$this->region_name = trim($params['CustomerSearch']['region_name']);
if ($isname) {
$sql .= " and ";
}
$sql .= " r.id=" . $params['CustomerSearch']['region_name'];
}
if (isset($params['CustomerSearch']['town_name']) && $params['CustomerSearch']['town_name'] !== '') {
$this->town_name = trim($params['CustomerSearch']['town_name']);
if ($isname || $isregion) {
$sql .= " AND t.id = {$this->town_name}";
}
}
if (isset($params['CustomerSearch']['balancex']) && $params['CustomerSearch']['balancex'] !== '') {
$this->balancex = trim($params['CustomerSearch']['balancex']);
if ($isbalance) {
$sql .= " AND balancex > {$isbalance}";
}
}
}
# town where clause.
$result = Yii::$app->db->createCommand($sql)->queryAll();
return $result;
1条答案
按热度按时间wfsdck301#
不能在where子句中使用计算字段。你需要使用having子句。
https://stackoverflow.com/a/16068737/4338862.