使用基于常量值的SELECT CASE

时间:2013-05-03 09:09:37

标签: php mysql pdo

我有这个名为设备的ff表:

+----------+----------+-----------+-------------+----------+---------+
| equip_id | chara_id | weapon_id | headgear_id | armor_id | ring_id |
+----------+----------+-----------+-------------+----------+---------+
|        3 |        1 |         3 |           5 |        9 |       8 |
|        5 |        3 |         3 |           5 |        3 |       8 |
|        6 |        4 |         7 |           5 |        3 |       8 |
|        7 |        5 |         4 |           5 |        3 |       8 |
|        8 |        6 |         3 |           5 |        2 |       8 |
|       10 |        8 |         3 |           5 |        2 |       8 |
+----------+----------+-----------+-------------+----------+---------+

我有这个长期的陈述:

switch ($equip->item_type) {
        case '1':
            # Weapon

            $sql_equip = "UPDATE equipment SET weapon_id = :item_id WHERE chara_id = :chara_id";  
            break;

        case '2':
            # Armor
            $sql_equip = "UPDATE equipment SET armor_id = :item_id WHERE chara_id = :chara_id";
            break;

        case '3':
            # Ring
            $sql_equip = "UPDATE equipment SET ring_id = :item_id WHERE chara_id = :chara_id";
            break;

        case '4':
            # Headgear
            $sql_equip = "UPDATE equipment SET headgear_id = :item_id WHERE chara_id = :chara_id";
            break;

        default:
            # do nothing...
            break;
    }

我在网上看到一些查询,你可以在你的查询中使用case语句,我搜索网络,我似乎无法找出一个正确的使用。

我希望它在1个语句中,因为我将它包装在一个transact函数上,并且还将添加另一行mysql语句。所以不是做4x2(当前)我只会做2(如果这可以在1个查询中完成)mysql查询。

2 个答案:

答案 0 :(得分:1)

你可以有这个陈述,

UPDATE  equipment 
SET     weapon_id = CASE WHEN :itemtype = 1 THEN :item_id ELSE weapon_id END,
        armor_id = CASE WHEN :itemtype = 2 THEN :item_id ELSE armor_id END,
        ring_id = CASE WHEN :itemtype = 3 THEN :item_id ELSE ring_id END,
        headgear_id = CASE WHEN :itemtype = 4 THEN :item_id ELSE headgear_id END
WHERE   chara_id = :chara_id

但您需要传递三个值,:itemtype:item_id:chara_id

答案 1 :(得分:0)

$fieldnames = array(1=>'weapon', 'armor', 'ring', 'headgear');
if (isset($fieldnames[$equip->item_type])) {
    $field = $fieldnames[$equip->item_type].'_id';
    $sql_equip = "UPDATE equipment SET $field = :item_id WHERE chara_id = :chara_id";
}