如何将静态查询转换为动态查询?

时间:2014-10-30 03:47:05

标签: php mysql

我的问题是如何将以下书面查询更改为动态查询。 表结构和查询如下:

班级表

class_id              class_name
  1                     1st
  2                     2nd

费用类型表

fee_type_id         fee_name
   1                Admission Fee
   2                Tution Fee

费用计划表

fee_plan_id         fee_type_id       class_id      fee_value
    1                     1                1            3000
    2                     2                1            400

fee_write_off表

fee_write_off_id           fee_id           months
     1                        1              4
     2                        2              1
     3                        2              2
     4                        2              3
     5                        2              4
     6                        2              5
     7                        2              6
     8                        2              7
     9                        2              8
    10                        2              9
    11                        2              10
    12                        2              11
    13                        2              12

如果使用php循环或mysql存储过程cursur循环等从前端复选框中选择月份名称,如何构建动态查询我不知道如何动态执行此查询。

SELECTfee_name,
   SUM(CASE months  WHEN  4 THEN amount ELSE 0 END) AS `April`,
   SUM(CASE months WHEN  5 THEN amount ELSE 0 END) AS `May`,
   SUM(CASE months WHEN  6 THEN amount ELSE 0 END) AS `June`,
   SUM(CASE months WHEN  7 THEN amount ELSE 0 END) AS `July`,
   SUM(CASE months WHEN  8 THEN amount ELSE 0 END) AS `August`,
   SUM(CASE months WHEN  9 THEN amount ELSE 0 END) AS `September`,
   SUM(CASE months WHEN 10 THEN amount ELSE 0 END) AS `October`,
   SUM(CASE months WHEN 11 THEN amount ELSE 0 END) AS `November`,
   SUM(CASE months WHEN 12 THEN amount ELSE 0 END) AS `December`,
   SUM(CASE months WHEN  1 THEN amount ELSE 0 END) AS `January`,
   SUM(CASE months WHEN  2 THEN amount ELSE 0 END) AS `February`,
   SUM(CASE months WHEN  3 THEN amount ELSE 0 END) AS `March`,
   SUM(amount) AS `Total`
FROM fee_type
JOIN fee_writeoff USING(fee_id)
JOIN fee_plan USING(fee_id)
GROUP BY fee_name WITH ROLLUP

0 个答案:

没有答案