19

当 SQL 查询中的字段很长时,如何使其更具可读性?

例如:

public function findSomethingByFieldNameId($Id) {
        $sql = "SELECT field1, field2, field3 as Field3_Something, field4, field5, field6, field7, field8, field9
                      FROM table
               JOIN table2 AS TNS ON TNS.id = table.id
                      WHERE something = 1";
 return $this->db->fetchData($sql, null, 'all');
    }
4

5 回答 5

29

我更喜欢 Heredoc 语法,尽管 Nowdoc 也适用于您的示例:

赫雷多克:

http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Nowdoc: http ://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc

两者的优点是您可以直接在该块中复制和粘贴 SQL,而无需对其进行转义或格式化。如果您需要包含解析,例如处理双引号字符串中的变量,您将使用 Heredoc。Nowdoc 的行为类似于单引号。

诺德克:

public function findSomethingByFieldNameId($Id) {
    $sql = <<<'SQL'
    SELECT field1, field2, field3 as Field3_Something, field4, field5, field6, field7, field8, field9
    FROM table
    JOIN table2 AS TNS ON TNS.id = table.id
    WHERE something = 1
SQL;

    return $this->db->fetchData($sql, null, 'all');
}

赫雷多克:

public function findSomethingByFieldNameId($Id) {
    $sql = <<<SQL
    SELECT field1, field2, field3 as Field3_Something, field4, field5, field6, field7, field8, field9
    FROM table
    JOIN table2 AS TNS ON TNS.id = table.id
    WHERE something = '$Id'
SQL;

    $sql = mysql_real_escape_string($sql);

    return $this->db->fetchData($sql, null, 'all');
}
于 2012-10-08T14:04:49.593 回答
11

您可以像这样连接它以使其更具可读性:

$sql = "SELECT field1, field2, field3 as Field3_Something,";
$sql.= " field4, field5, field6, field7, field8, field9";
$sql.= " FROM table JOIN table2 AS TNS ON TNS.id = table.id";
$sql.= " WHERE something = 1";

注意:确保在连接查询时,不要忘记在双引号之间开始新行之前留下空格,否则会出现查询无效错误

于 2012-10-08T14:03:08.863 回答
1
 $sql = "SELECT field1,
                field2,
                field3 as Field3_Something,
                field4,....
         FROM table
         JOIN table2 AS TNS ON TNS.id = table.id
         WHERE something = 1";
于 2012-10-08T14:03:37.633 回答
1

这只是另一种方式。

请注意,数组连接比字符串连接快。

$sql = join(" \n", Array(
    'SELECT ',
    '    [...fields...]',
    '    [...more fields...]',
    'FROM table',
    'JOIN table2 AS TNS ON TNS.id = table.id',
    'WHERE something = 1',
));
于 2016-12-16T16:53:48.743 回答
-1
<?php
   public function findSomethingByFieldNameId($Id) {
        $sql = "SELECT 
                    field1, 
                    field2, 
                    field3 as Field3_Something, 
                    field4, 
                    field5, 
                    field6, 
                    field7, 
                    field8, 
                    field9
                FROM 
                    table
                JOIN table2 AS TNS 
                    ON TNS.id = table.id
                WHERE 
                    something = 1";
        return $this->db->fetchData($sql, null, 'all');
}
?>
于 2012-11-29T13:03:46.027 回答