0

CodeIgniter Version: 2.1.3
MySQL Version: 5.5.30
MySQL Engine: MyISAM

Query:

$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);

The user-defined variables (@cut_off_pay, @total_days, etc..) are not working, it returns 0/NULL values

1 Answer 1

1

IMHO

  1. You don't need any user variables for this
  2. You don't need WHERE clause in your case that duplicates a join condition
  3. And you don't even need to join users with attendance table since you don't use any values from it and a choice of a LEFT JOIN and attendance table being on the left of it is highly questionable

That being said either do

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

You don't even need to give aliases to derived columns in your select since you insert them, but that just improves readability and you can always use that select on its own e.g. for testing purposes

or simply

$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";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.