I've tried this code:
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
On SQL (and work well), and now I need this code to be implemented on codeigniter with query()
. The problem is I can't insert
SET @num := 0, @type := NULL;
On query(), because it's always give error messages when I inserted it.
I have done this:
$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);
and I cant write anything before SELECT syntax because it will return error message when I try it.
You will have to run two seperate queries for this
$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);