如果条件为MYSQL,则切换值

时间:2014-02-24 10:02:07

标签: mysql sql

我想在sql查询中添加条件时切换值,但我不知道sql中if else语句的确切工作方式。

这是我的疑问:

数据库:

attr_id
st_id
prod_id
value

数据:

$attr_id1   = "75";
$attr_id2   = "76";
$st_id      = array('2','2','2','2');
$prod_id    = array('2','3','4');
$value  = array('150','200','300');

SQL:

"INSERT INTO table
    (attr_id, st_id, prod_id, value)
    VALUES (IF(value from $attr_id2 is < less  that $value switch to $attr_id2 else to $attr_id1), ".$st_id.", ".$prod_id.", ".$value.")
    ON DUPLICATE KEY UPDATE 
    value = (".$value.")";
    "WHERE attr_id = ".$attr_id1." //OR ATTR_ID2
    AND st_id = ".$st_id."
    AND prod_id = ".$prod_id."
"

DATATABLE:

attr_id   st_id  prod_id    value
75          2       2       150
76          2       2       200
75          2       3       300
76          2       3       290
76          2       4       200

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用CASE

INSERT INTO TABLE (attr_id, st_id, prod_id, VALUE) 
VALUES
  (
    CASE
      WHEN ".$attr_id2." < ".$attr_id1."
      THEN ".$attr_id2." 
      ELSE ".$attr_id1." 
    END,
    ".$st_id.",
    ".$prod_id.",
    ".$value."
  ) .....