codeigniter和mysql用户定义的变量不起作用

时间:2013-07-04 03:28:13

标签: mysql codeigniter variables

CodeIgniter版本:2.1.3
MySQL版本:5.5.30
MySQL引擎:MyISAM

查询:

$query = "INSERT INTO new_table
      (
        user_id,
        cut_off_pay,
        total_days,
        rate_per_day,
        rate_per_hour,
      )
      (
        SELECT
          u.id,
          @cut_off_pay := (u.current_salary / 2) ,
          @total_days := 10,
          @rate_per_day := (@cut_off_pay / @total_days),
          @rate_per_hour := (@rate_per_day / 8)
        FROM attendance a
        LEFT JOIN users u
          ON a.user_id = u.id
        WHERE a.user_id = u.id
        GROUP BY a.user_id
      )";              
$this->db->query($query);

用户定义的变量(@ cut_off_pay,@ length_days等)不起作用,它返回0 / NULL值

1 个答案:

答案 0 :(得分:1)

IMHO

  1. 您不需要此
  2. 的任何用户变量
  3. 您的案例中不需要复制连接条件的WHERE子句
  4. 您甚至不需要将users加入attendance表,因为您不使用其中的任何值以及选择LEFT JOINattendance在它左边的桌子是非常值得怀疑的
  5. 有人这么说

    $query = "INSERT INTO new_table
              (
                user_id,
                cut_off_pay,
                total_days,
                rate_per_day,
                rate_per_hour
              )
              SELECT u.id,
                     u.current_salary / 2          cut_off_pay,
                     10                            total_days,
                     u.current_salary / 2 / 10     rate_per_day,
                     u.current_salary / 2 / 10 / 8 rate_per_hour
                FROM attendance a LEFT JOIN users u
                  ON a.user_id = u.id
               GROUP BY a.user_id";
    

    您甚至不需要在您的选择中为派生列提供别名,因为您插入它们,但这只是提高了可读性,您可以随时使用该选择,例如用于测试目的

    或只是

    $query = "INSERT INTO new_table
              (
                user_id,
                cut_off_pay,
                total_days,
                rate_per_day,
                rate_per_hour
              )
              SELECT id,
                     current_salary / 2          cut_off_pay,
                     10                            total_days,
                     current_salary / 2 / 10     rate_per_day,
                     current_salary / 2 / 10 / 8 rate_per_hour
                FROM users";