Execute complex queries, Problem
I'm trying to execute a bit complex query and result is strange.
Database structure and data
CREATE TABLE IF NOT EXISTS `cat` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key: Unique ID.',
`name` varchar(255) DEFAULT NULL COMMENT 'Category title',
`group` varchar(1) DEFAULT NULL,
`type` varchar(255) DEFAULT NULL COMMENT 'Category title',
`parent` int(11) NOT NULL DEFAULT '0' COMMENT 'Category Parent ID',
`active` int(11) DEFAULT '0' COMMENT 'Category active status',
`weight` int(11) DEFAULT '0',
`slug` varchar(255) DEFAULT NULL COMMENT 'Category url alias',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;
INSERT INTO `cat` (`id`, `name`, `group`, `type`, `parent`, `active`, `weight`, `slug`) VALUES
(1, 'Category 1', '0', 'a', 0, 1, 0, NULL),
(2, 'Category 2', '0', 'a', 0, 1, 0, NULL),
(3, 'Category 3', '0', 'a', 0, 1, 0, NULL),
(4, 'Sub Category 1 - 1', '1', 'b', 1, 1, 0, NULL),
(5, 'Sub Category 1 - 2', '1', 'b', 1, 1, 0, NULL),
(6, 'Sub Category 1 - 3', '1', 'b', 1, 1, 0, NULL),
(7, 'Sub Category 2 - 1', '2', 'c', 2, 1, 0, NULL),
(8, 'Sub Category 2 - 2', '2', 'c', 2, 1, 0, NULL),
(9, 'Sub Category 2 - 3', '2', 'c', 2, 1, 0, NULL),
(10, 'Sub Category 3 - 1', '3', 'd', 3, 1, 0, NULL),
(11, 'Sub Category 3 - 2', '3', 'd', 3, 1, 0, NULL),
(12, 'Sub Category 3 - 3', '3', 'd', 3, 1, 0, NULL);
MySQL Query
SELECT * FROM (SELECT *, @num := IF(@group = parent, @num + 1, 1) AS num, @group := parent AS dummy FROM categories WHERE parent IN (SELECT id FROM categories WHERE parent = 0) ORDER BY parent, name) AS temp WHERE num <= 1
PHP Code
$query = $this->db->query('SELECT * FROM (SELECT *, @num := IF(@group = parent, @num + 1, 1) AS num, @group := parent AS dummy FROM cat WHERE parent IN (SELECT id FROM cat WHERE parent = 0) ORDER BY parent, name) AS temp WHERE num <= 1');
print_r($query->result_array());
Executing an SQL Query in Console or over PHPMyAdmin/HeidiSQL, gives 3 results. Executing the same query in CodeIgniter gives all rows in DB.
Is there something where Codeigniter get problems?!
I remember having to initialize my variables with a separate query first when doing this, Something like:
$this->db->query("SELECT 0, 0 INTO @num, @group");
Then running the query. I don't know why I did that in time, but I remember having it work this way.
Not a CI issue.
Why is that not a CI issue if that query working perfect directly in MySQL, pure PHP but not in CI?
Because it doesn't work directly either if you haven't initialized your variables.