如何将CASE条件与数据库数据

时间:2016-08-02 17:43:55

标签: php mysql

我试图将CASE CONDITION与我database的数据一起使用,但它无效

这是我的代码:

SELECT 
  CASE WHEN `vessel_name` == 'SAMMY' AND `vessel_status` == 'AVAILABLE PROPOSE LINEUP'
      THEN 'asdf' 
  END 
FROM `pending_list`

如果声明为echo我正试图AVAILABLE PROPOSE LINEUP TRUE

这是我的database
列名vessel_name行值SAMMY
列名vessel_status行值AVAILABLE PROPOSE LINEUP

如果条件为真,则结果必须为:

Vessel Name:  SAMMY              
Vessel Status:  AVAILABLE PROPOSE LINEUP

如果条件为假,则结果必须为:

Vessel Name:  SAMMY              
Vessel Status:  NO AVAILABLE PROPOSE LINEUP

以下是我的全部代码:

<table class="table table-hover table-condensed" data-toggle="table" id="resultTable">
            <thead class="thead-inverse">
            <tr>
                <th data-sortable="true">Vessel Name</th>
                <th data-sortable="true">Vessel Status</th>
            </tr>
            </thead>
            <tr>
                <th>SAMMY</th>
                <th><?php "SELECT CASE WHEN `vessel_status` = 'AVAILABLE PROPOSE LINEUP' 
            THEN 'AVAILABLE PROPOSE LINEUP' 
            ELSE 'NO AVAILABLE PROPOSE LINEUP' 
       END as `vessel_status`
FROM `pending_list`
WHERE `vessel_name` = 'SAMMY'"  ?></th>
            </tr>

1 个答案:

答案 0 :(得分:0)

如果你提供一些样本数据会很好。基于我的假设,我已经给出了我的意见。请检查......

您可以编写如下的SQL

"SELECT vessel_name, CASE WHEN `vessel_status` = 'AVAILABLE PROPOSE LINEUP' THEN 'AVAILABLE PROPOSE LINEUP' ELSE 'NO AVAILABLE PROPOSE LINEUP' END as vessel_status 
FROM `pending_list`"

另外在html部分中,必须调用mysql连接和查询执行方法来获取数据。目前尚不清楚此查询将从表中获取多少数据。如果正在提取超过1条记录,则必须通过它进行循环,否则只需按以下方式显示数据

$sql = "SELECT vessel_name, CASE WHEN `vessel_status` = 'AVAILABLE PROPOSE LINEUP' THEN 'AVAILABLE PROPOSE LINEUP' ELSE 'NO AVAILABLE PROPOSE LINEUP' END as vessel_status 
FROM `pending_list`";

$conn = mysql_connect('host','username','password') or die(mysql_error);
mysql_select_db(db_name);
$recordset = mysql_query($sql ,$conn) or die(mysql_error);

如果只有一条记录,那么

$obj = mysql_fetch_object($recordset);
$vessel_status = $obj->vessel_status ;
$vessel_name = $obj->vessel_name ;

如果有多个记录正在进行,则循环通过它

while($obj = mysql_fetch_object($recordset))
{
    $vessel_status = $obj->vessel_status ;
    $vessel_name = $obj->vessel_name ;
}


mysql_free_result($recordset);