2013-07-04 42 views
0

笨版本:2.1.3
的MySQL版本:30年5月5日
MySQL的引擎:MyISAM數據笨和mysql用戶自定義變量不工作

查詢:

$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值

回答

1

恕我直言

  1. 你並不需要爲這個
  2. 任何用戶變量你不需要在你的情況WHERE條款,複製連​​接條件
  3. 你甚至不需要與attendance表加入users因爲你請不要使用任何價值和LEFT JOINattendance表是在它的左邊的選擇是非常值得懷疑的

話雖這麼說,無論是做

$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"; 
+0

@scoohh有沒有幫助? – peterm