【问题标题】:Using a table-alias in Kohana queries?在 Kohana 查询中使用表别名?
【发布时间】:2010-04-04 22:46:20
【问题描述】:

我正在尝试在 Kohana 中使用 $this->db 运行一个简单的查询,但是当我尝试在查询中为表使用别名时遇到了一些语法问题:

$result = $this->db
  ->select("ci.chapter_id, ci.book_id, ci.chapter_heading, ci.chapter_number")
  ->from("chapter_info ci")
  ->where(array("ci.chapter_number" => $chapter, "ci.book_id" => $book))
  ->get();

在我看来,这应该可以正常工作。我是说“chapter_info”应该被称为“ci”,但由于某种原因这并没有被占用。错误非常简单:

There was an SQL error: Table 'gb_data.chapter_info ci' doesn't exist - 
SELECT `ci`.`chapter_id`, `ci`.`book_id`, `ci`.`chapter_heading`, 
       `ci`.`chapter_number`
FROM (`chapter_info ci`) 
WHERE `ci`.`chapter_number` = 1
  AND `ci`.`book_id` = 1

如果我使用完整的表名而不是别名,我会得到预期的结果而不会出错。这需要我编写更详细的查询,这并不理想。

有没有办法在 Kohana 的查询构建器中为表使用较短的名称?

【问题讨论】:

    标签: mysql database syntax kohana


    【解决方案1】:

    在 Kohana 3 中就足够了:

    ->from( array('table_name', 'alias') )
    

    这将创建包含以下内容的查询:

    FROM 'table_name' AS 'alias'
    

    我已经对其进行了测试,并且可以正常工作。祝你好运。

    【讨论】:

    • 顺便说一句。如果您想传递任何应该跳过转义的内容,您应该通过DB::expr() 提供它,而不是提供简单的字符串。例如。传递给查询生成器时,您应该使用DB::expr('COUNT(*)') 而不是COUNT(*)
    【解决方案2】:
    $result = $this->db
      ->select("ci.chapter_id, ci.book_id, ci.chapter_heading, ci.chapter_number")
      ->from("'chapter_info' AS ci")
      ->where(array("ci.chapter_number" => $chapter, "ci.book_id" => $book))
      ->get();
    

    应该可以。因为您必须在 AS 关键字和要缩短的新表名之前将原始表名放在引号中。

    【讨论】:

      【解决方案3】:

      尝试使用像->from("chapter_info as ci")这样的“as”关键字,也许查询生成器会这样识别它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多