如果表中不存在另一列,则SQL语句按一列排序

时间:2017-09-08 12:19:46

标签: mysql sql

首先,抱歉可能是一个简单的问题,但是,我无法理解如何解决在我构建的Web应用程序中使用的SQL查询。

我的数据库中有许多表格,在网站上显示时需要以不同的方式订购。目前我的代码是:

//get the data from a table (request from the user)
$sql = "SELECT * FROM `$TableName` ";
$result = mysqli_query($dbcon, $sql);
$count = mysqli_num_rows($result);

//Get the template of the table 
$sql = "SELECT * FROM tableIndex WHERE TableName = '$TableName'";
$resultTemplate = mysqli_query($dbcon, $sql);
while ($row = mysqli_fetch_array($resultTemplate)) {
    $Template = $row['Template'];
            }

这将从一个表中获取数据,然后检查用于在屏幕上显示信息的预定义模板。

模板示例如下所示:

echo '      
                    <thead>
                     <tr class="row-1">
                        <th class="column-1">Club</th>
                        <th class="column-2">P</th>
                        <th class="column-3">Shots</th>
                        <th class="column-4">Pts</th>
                    </tr>
                    </thead>
                    <tbody>';

                    if ($count == 0){
                    $output = 'error';
                }else {
                    while ($row = mysqli_fetch_array($result)) {
                    $ID = $row['ID'];
                    $one = $row['ColumnOne'];
                    $two = $row['ColumnTwo'];
                    $three = $row['ColumnThree'];
                    $four = $row['ColumnFour'];

                    $output =' 
                        <tr class="d1">
                        <td>'.$one.'</td>
                        <td>'.$two.'</td>
                        <td>'.$three.'</td>
                        <td>'.$four.'</td>
                       </tr>

                  ';

        echo $output;

我现在需要修改$sql = SELECT * FROM $TableName以包含 ORDER BY 个案,例如;

  • 如果“ColumnFive”存在,则“ORDER BY ColumnFour DESC”
  • 如果“ColumnSix”存在,则“ORDER BY ColumnFive DESC”
  • 如果存在“ColumnSeven”,则不要订购

非常感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:1)

首先检查列是否存在

$result = mysql_query("SHOW COLUMNS FROM `$TableName` LIKE 'ColumnName'");
$exists = (mysql_num_rows($result))?TRUE:FALSE;

然后相应地构建您的主要查询