2

私はこのコードを試しました:

SET @num := 0, @type := NULL;
SELECT categories_name, products_name, products_url, categories_id, 
       @num := IF( @type = categories_name, @num +1, 1 ) AS row_number,
       @type := categories_name AS dummy
  FROM (
        SELECT categories_name, products_name, products_url, ptc.categories_id
          FROM toc_products_description pd
         INNER JOIN toc_products_to_categories ptc ON pd.products_id = ptc.products_id
         INNER JOIN toc_categories_description cd ON cd.categories_id = ptc.categories_id
               AND pd.language_id =1
               AND cd.language_id =1
        ) AS x
 GROUP BY x.categories_name, x.products_name, x.products_url, x.categories_id
HAVING row_number <=2

SQLで(そしてうまく機能します)、そして今、このコードをcodeigniterで実装する必要がありますquery(). 問題は、挿入できないことです

SET @num := 0, @type := NULL;

query() では、挿入すると常にエラー メッセージが表示されるためです。

私はこれをしました:

$query="SELECT categories_name, products_name, products_url, categories_id, @num := IF( @type := categories_name, @num +1, TRUE) AS row_number, @type := categories_name AS dummy
                FROM (
                SELECT categories_name, products_name, products_url, ptc.categories_id
                FROM toc_products_description pd
                INNER JOIN toc_products_to_categories ptc ON pd.products_id = ptc.products_id
                INNER JOIN toc_categories_description cd ON cd.categories_id = ptc.categories_id
                AND pd.language_id =1
                AND cd.language_id =1
                ) AS x
                GROUP BY x.categories_name, x.products_name, x.products_url, x.categories_id
                HAVING row_number <=5";        
        $result = $this->db->query($query);

SELECT 構文の前に何かを書くことはできません。試してみるとエラー メッセージが返されるからです。

4

3 に答える 3

7

これには2つの別々のクエリを実行する必要があります

$query  =   "SET @num := 0, @type := NULL";
$this->db->query($query);
$new_query  =   "
                SELECT categories_name, products_name, products_url, categories_id, 
                       @num := IF( @type = categories_name, @num +1, 1 ) AS row_number,
                       @type := categories_name AS dummy
                  FROM (
                        SELECT categories_name, products_name, products_url, ptc.categories_id
                          FROM toc_products_description pd
                         INNER JOIN toc_products_to_categories ptc ON pd.products_id = ptc.products_id
                         INNER JOIN toc_categories_description cd ON cd.categories_id = ptc.categories_id
                               AND pd.language_id =1
                               AND cd.language_id =1
                        ) AS x
                 GROUP BY x.categories_name, x.products_name, x.products_url, x.categories_id
                HAVING row_number <=2";
$this->db->query($new_query);               
于 2013-02-22T10:37:27.253 に答える
0

SQL でストアド プロシージャを作成し、query() からストアド プロシージャを呼び出します。

于 2013-02-22T07:41:01.037 に答える