INSERT INTO语句中的case语句

时间:2015-06-14 22:22:22

标签: php mysql insert case insert-into

我有以下register.php代码

<?php
if( $_POST )
{
  include("php_connect/php_connect.php");

  $start_year  = $_POST['start_year'];
  $start_month = $_POST['start_month'];
  $start_day = $_POST['start_day'];
  $start_hour = $_POST['start_hour'];
  $start_minute = $_POST['start_minute'];
  $place = $_POST['place'];
  $salah = $_POST['salah'];
  $rakat = implode(",", $_POST['rakat']); 

  $query = "INSERT INTO performed_salah 
           (year, month, date, time, place, prayer, rakat, reg_date) VALUES 
           ('$start_year', '$start_month', '$start_day', ('$start_hour:$start_minute'), '$place', '$salah', '$rakat', NOW())";

  if ($conn->query($query) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $query . "<br>" . $conn->error;
}

$conn->close();
}
?>

在我的表中,我有一个列性能。 我正在尝试创建一个类似于

的CASE STATEMENT
CASE WHEN prayer='A' and rakat=('Rakat-A,Rakat-B') then performance = 100%
     WHEN prayer='A' and rakat=('Rakat-A') or rakat=('Rakat-B') then performance = 50%
     WHEN prayer='B' and rakat=('Rakat-A,Rakat-B,Rakat-C,Rakat-D) then performance = 100%
WHEN prayer = 'B' and rakat=('Rakat-A,Rakat-B,Rakat-C') then performace = 75%
WHEN prayer = 'B' and rakat=('Rakat-A,Rakat-B') then performace = 50%
WHEN prayer = 'B' and rakat=('Rakat-A') then performace = 25%

如何制作它?

我尝试了这个,但收到了错误:

"INSERT INTO performed_salah('$start_year', '$start_month', '$start_day', ('$start_hour:$start_minute'), '$place', '$salah', '$rakat', 
(case when prayer = 'fajar' and (rakat='2Sunnat,2Faradh') then " . '100%' . "    
      when prayer = 'fajar' and (rakat='2Sunnat' or rakat='2Faradh') then " . ' '50%' . "end) '$performance', NOW())";

1 个答案:

答案 0 :(得分:1)

这是您的查询:

INSERT INTO performed_salah(year, month, date, time, place, prayer, rakat, reg_date)
     VALUES  ('$start_year', '$start_month', '$start_day', ('$start_hour:$start_minute'), '$place', '$salah', '$rakat', NOW());

这很有道理。你的第二个查询毫无意义。但是,一个基本问题是case语句不能使用表中的列名。您可以在事后使用update执行此操作,但在插入中,您需要用于插入的变量。像这样:

INSERT INTO performed_salah(year, month, date, time, place, prayer,
            rakat, reg_date, performance)
     VALUES  ('$start_year', '$start_month', '$start_day', ('$start_hour:$start_minute'),
              '$place', '$salah', '$rakat',
               (case when '$prayer' = 'fajar' and '$rakat' = '2Sunnat,2Faradh'
                     then '100%'   
                     when '$prayer' = 'fajar' and '$rakat' in ('2Sunnat', '2Faradh')
                     then '50%' 
               end),
              NOW());

仍有很大的改进空间。像performance这样的字段看起来像一个数字,所以你应该这样存储它。如果使用参数,SQL代码会更安全,而不是显式地将值放在字符串中。但这可能会让你知道如何继续。