0

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、@total_days 等)不起作用,它返回 0/NULL 值

4

1 回答 1

1

恕我直言

  1. 您不需要任何用户变量
  2. 在您的情况下,您不需要WHERE重复连接条件的子句
  3. 而且你甚至不需要加入userstableattendance因为你不使用它的任何值并且选择 aLEFT JOINattendancetable 在它的左边是非常值得怀疑的

话虽如此,要么做

$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";
于 2013-07-04T03:41:01.440 回答