如何调用函数是sql select?

时间:2016-09-06 09:29:20

标签: php mysql sql

我有sql select,我需要为status_bid字段使用一些函数吗?像这样:

        SELECT 
             `N`.`_id` as `_id`,
             `N`.`created_at` as `created_at`,
             CASE
                WHEN `N`.`status_bid` = 1 THEN "'.$this->getBidStatusString(1).'"
                WHEN `N`.`status_bid` = 2 THEN "'.$this->getBidStatusString(2).'"
                WHEN `N`.`status_bid` = 3 THEN "'.$this->getBidStatusString(3).'"
                WHEN `N`.`status_bid` = 4 THEN "'.$this->getBidStatusString(4).'"
                WHEN `N`.`status_bid` = 5 THEN "'.$this->getBidStatusString(5).'"
                WHEN `N`.`status_bid` = 6 THEN "'.$this->getBidStatusString(6).'"
                WHEN `N`.`status_bid` = 10 THEN "'.$this->getBidStatusString(10).'"
                WHEN `N`.`status_bid` = 11 THEN "'.$this->getBidStatusString(11).'"                    
                ELSE "0"
             END as `status_bid`,                 
             ..........
             ..........

CASE WHEN ELSE END对我来说并不好。如何改变

    if (`N`.`status_bid` IS NOT NULL) {
        '".$this->getBidStatusString(`N`.`status_bid`).'" as `status_bid`  
    }

我有php功能

/**
 * @return string
 */
public function getBidStatusString($id)
{
    if (array_key_exists($id, Bit::getBidStatusSerialized())) {
        return Bit::getBidStatusSerialized()[$id];
    }
}

这在sql中是可能的吗?

2 个答案:

答案 0 :(得分:1)

假设您在PHP中执行此操作并在字符串中构建查询,稍后将在查询中使用,那么这是完全可能的。

请参阅下面的示例代码。

<?php
class aa
{
    public $arr = array('aa','bb','cc');

    public function getBidStatusString($id){
        return $this->arr[$id];
    }

    public function query()
    {
        $q = "SELECT
             `N`.`_id` as `_id`,
             `N`.`created_at` as `created_at`,
             CASE
                WHEN `N`.`status_bid` = 1 THEN '{$this->getBidStatusString(1)}'
                WHEN `N`.`status_bid` = 1 THEN '{$this->getBidStatusString(2)}'
                ELSE `0`
             END as `status_bid`";

        return $q;

    }
}

$aa = new aa();
echo $aa->query();

将返回:

SELECT
     `N`.`_id` as `_id`,
     `N`.`created_at` as `created_at`,
     CASE
        WHEN `N`.`status_bid` = 1 THEN 'bb'
        WHEN `N`.`status_bid` = 1 THEN 'cc'
        ELSE `0`
     END as `status_bid`

答案 1 :(得分:0)

不要在SQL中执行此操作。从mysql获取数据后,迭代您的数据。或者,您可以在需要时调用 getBidStatusString 。例如

<span><?=Bit::getBidStatusSerialized()[$data['id']]?>