0

当我添加最后一行“和@summ > 0(任何条件)”时,它返回空结果。我做错了什么?如何正确地将@summ传递给 where 子句?

 select
      nore.nis as nore_curent,
      field_funds.value,
     (select @summ :=
        sum(field_amount.value - field_amount_tip.value)
          from
        nore
        inner join field_project on nore.nis = field_project.id
        inner join field_funds on field_funds.id = field_project.target_id
        inner join field_amount on nore.nid = field_data_field_amount.id
        inner join field_amount_tip on nore.nis = field_amount_tip.id
          where
        nore.`s` = 1
          and
        nore.`t` = 'p'
          and
        field_project.target_id = nore_curent) as amount
      from
       nore
      inner join field_funds on nore.nis = field_funds.id
       where
      nore.`s` = 1
       and
      nore.`t` = 'pp'
       and @summ > 0
4

1 回答 1

0

保留一些与 Select 语句评估的概念(或逻辑)顺序相关的基础知识是值得的 - 在这里:http

://tinman.cs.gsu.edu/~raj/sql/node22.html顺序是:

  1. 在哪里
  2. 通过...分组
  3. 拥有
  4. 订购方式
  5. 选择


WHERE 子句在 SELECT 子句之前 评估(执行) 。
的值@summ是在(主查询的)SELECT 子句中计算的,因此当 DMBS 评估 WHERE 子句时,它的值是未知的。

Unknown = NULL

因此此查询不会按预期工作。

将查询重写为:

select
      nore.nis as nore_curent,
      field_funds.value,
     (select sum(field_amount.value - field_amount_tip.value)
          from
        nore
        inner join field_project on nore.nis = field_project.id
        inner join field_funds on field_funds.id = field_project.target_id
        inner join field_amount on nore.nid = field_data_field_amount.id
        inner join field_amount_tip on nore.nis = field_amount_tip.id
          where
        nore.`s` = 1
          and
        nore.`t` = 'p'
          and
        field_project.target_id = nore_curent) as amount
      from
       nore
      inner join field_funds on nore.nis = field_funds.id
       where
      nore.`s` = 1
       and
      nore.`t` = 'pp'
       and 0 < (select sum(field_amount.value - field_amount_tip.value)
                  from nore
                  inner join field_project on nore.nis = field_project.id
                  inner join field_funds on field_funds.id = field_project.target_id
                  inner join field_amount on nore.nid = field_data_field_amount.id
                  inner join field_amount_tip on nore.nis = field_amount_tip.id
                  where
                    nore.`s` = 1
                    and
                    nore.`t` = 'p'
                    and
                    field_project.target_id = nore_curent
)
于 2013-10-10T20:07:12.160 回答