where子句中的mysql变量

时间:2013-10-10 14:21:06

标签: mysql

当我添加最后一行“和@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

1 个答案:

答案 0 :(得分:0)

值得重新记录一些与Select语句的概念(或逻辑)评估顺序相关的基础知识 - 这里:http://tinman.cs.gsu.edu/~raj/sql/node22.html

订单是:

  1. FROM
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. ORDER BY
  6. SELECT

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

    未知= 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
    )