I've tested the following SQL in phpMyAdmin and have confirmed that it works fine. However, when I try to use it in CodeIgniter as follows, I get error messages.
$this->db->order_by("vch_name", "asc");
$this->db->select('SELECT *, (SELECT COUNT(*) FROM tbl_contact WHERE fk_client_id = tbl_pro_client_id) AS count_contacts FROM tbl_pro_client');
$query = $this->db->get('tbl_pro_client', $num, $offset);
return $query;
Is this too complicated for a CI select, or is there a way around it? A more obvious answer of course is that I'm probably doing something incredibly stupid. And advice, pointers, etc greatly appreciated.
Only the actual fields you want to select should be given to the select() call (ie the SELECT keyword and FROM ... should not be there). Something like;
$this->db->order_by("vch_name", "asc");
$this->db->select('*, (SELECT COUNT(*) FROM tbl_contact WHERE fk_client_id=tbl_pro_client_id) AS count_contacts', false);
$query = $this->db->get('tbl_pro_client', $num, $offset);
return $query;
You should read more about database query manipulation click here
limit parameters are looking wrong, CI provide limit() function, try this code
And in select() function no need FROM table_name, and Use FALSE to skip (`)
$this->db->order_by("vch_name", "asc");
$this->db->select('SELECT *, (SELECT COUNT(*) FROM tbl_contact WHERE fk_client_id = tbl_pro_client_id) AS count_contacts', false);
$this->db->limit($num, $offset);
$query = $this->db->get('tbl_pro_client');
return $query;
Related
I have SQL query (see example).
But I can't find a way how I can write it in Query Builder.
Do you have any ideas how is it possible?
WITH main AS (
SELECT id FROM table1
)
SELECT * FROM table2
WHERE
table2.id IN (SELECT * FROM main)
I want to get format like:
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})->get();
but for WITH
Laravel has no native support for common table expressions.
I've created a package for it: https://github.com/staudenmeir/laravel-cte
You can use it like this:
$query = DB::table('table1')->select('id');
$result = DB::table('table2')
->withExpression('main', $query)
->whereIn('table2.id', DB::table('main')->select('id'))
->get();
Query builder has to be compatible with multiple database engines (mysql, postgresql, sql lite, sql server) and as such only offers support for common functionality.
Assuming your query returns data, you may be able to use the DB:select() method to execute a raw query.
$data = DB::select('WITH main AS (SELECT id FROM table1), SELECT * FROM table2 WHERE table2.id IN (SELECT * FROM main)');
The DB:select method also accepts a second parameter for using named bindings.
Alternatively there are packages available such as laravel-cte that will add the functionality to Eloquent/ Query Builder.
I am using Query builder on CodeIgniter 3. with Oracle DB.
I cannot create normal query. My query is:
$CI->db->query('c.*',false);
$CI->db->from('COUNTRIES c',false);
$CI->db->join('FILIALS as f','f.country_id=c.country_id',false);
$CI->db->where('f.FILIAL_ID',$id,false);
$query=$CI->db->get();
return $query->result('Country')[0];
This gives me a query
SELECT c.* FROM "COUNTRIES" "c" JOIN "FILIALS" as "f" ON "f"."country_id"="c"."country_id" WHERE f.FILIAL_ID = 7
But this query does not work, complaining that query is not correct. In Sqlplus the same problem.
But if I manually run in sqlplus,removing "as", and quotes in table fields and table names, it works normal.
This is my working query:
SELECT c.* FROM "COUNTRIES" c JOIN "FILIALS" f ON f.country_id=c.country_id WHERE f.FILIAL_ID = 7
How can I tell Query Builder, remove "as", and quotataion marks in query.
Try This Query :
$this->db->select('c.*',false);
$this->db->from('COUNTRIES c',false);
$this->db->join('FILIALS as f','f.country_id=c.country_id',false);
$this->db->where('f.FILIAL_ID',$id,false);
$query = $this->db->get();
return $query->result();
Remove AS from join
I thik its done.
$this->db->select('c.*',false);
$this->db->from('COUNTRIES c',false);
$this->db->join('FILIALS f','f.country_id=c.country_id',false);
$this->db->where('f.FILIAL_ID',$id,false);
$query = $this->db->get();
return $query->result();
I have the following mysql query. Could you please tell me how to write the same query in Codeigniter's way ?
SELECT * FROM myTable
WHERE trans_id IN ( SELECT trans_id FROM myTable WHERE code='B')
AND code!='B'
You can use sub query way of codeigniter to do this for this purpose you will have to hack codeigniter. like this
Go to system/database/DB_active_rec.php
Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now subquery writing in available
And now here is your query with active record
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
$this->db->_reset_select();
// And now your main query
$this->db->select("*");
$this->db->where_in("$subQuery");
$this->db->where('code !=', 'B');
$this->db->get('myTable');
And the thing is done. Cheers!!!
Note : While using sub queries you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Watch this too
How can I rewrite this SQL into CodeIgniter's Active Records?
Note : In Codeigntier 3 these functions are already public so you do not need to hack them.
$data = $this->db->get_where('columnname',array('code' => 'B'));
$this->db->where_in('columnname',$data);
$this->db->where('code !=','B');
$query = $this->db->get();
return $query->result_array();
Try this one:
$this->db->select("*");
$this->db->where_in("(SELECT trans_id FROM myTable WHERE code = 'B')");
$this->db->where('code !=', 'B');
$this->db->get('myTable');
Note: $this->db->select("*"); is optional when you are selecting all columns from table
try this:
return $this->db->query("
SELECT * FROM myTable
WHERE trans_id IN ( SELECT trans_id FROM myTable WHERE code='B')
AND code!='B'
")->result_array();
Is not active record but is codeigniter's way http://codeigniter.com/user_guide/database/examples.html
see Standard Query With Multiple Results (Array Version) section
you can use a simpler approach, while still using active record
$this->db->select("a.trans_id ,a.number, a.name, a.phone")
$this->db->from("Name_Of_Your_Table a");
$subQueryIn = "SELECT trans_id FROM Another_Table";
$this->db->where("a.trans_id in ($subQueryIn)",NULL);
I have a query similar to this:
SELECT username
FROM users
WHERE locationid IN
(SELECT locationid FROM locations WHERE countryid='$')
$ is a value I get from end user.
How could I run this query in CodeIgniter? I can't find a solution in CodeIgnite's user guide.
Thank you so much for your answers!
Regards!
Look here.
Basically you have to do bind params:
$sql = "SELECT username FROM users WHERE locationid IN (SELECT locationid FROM locations WHERE countryid=?)";
$this->db->query($sql, '__COUNTRY_NAME__');
But, like Mr.E said, use joins:
$sql = "select username from users inner join locations on users.locationid = locations.locationid where countryid = ?";
$this->db->query($sql, '__COUNTRY_NAME__');
Note that these solutions use the Code Igniter Active Records Class
This method uses sub queries like you wish but you should sanitize $countryId yourself!
$this->db->select('username')
->from('user')
->where('`locationId` in', '(select `locationId` from `locations` where `countryId` = '.$countryId.')', false)
->get();
Or this method would do it using joins and will sanitize the data for you (recommended)!
$this->db->select('username')
->from('users')
->join('locations', 'users.locationid = locations.locationid', 'inner')
->where('countryid', $countryId)
->get();
Also, to note - the Active Record Class also has a $this->db->where_in() method.
I think you can create a simple SQL query:
$sql="select username from user where id in (select id from idtables)";
$query=$this->db->query($sql);
and then you can use it normally.
I'm needeing to get all the child categories from the given to use in a where_in with active records of codeigniter.
The problem is that the second query get mixed with the main one breaking it completely.
Main Query
$this->db->select('artworks.*, users.id as owner, users.name as user_name');
$this->db->from('artworks');
$this->db->join('users', 'users.id = artworks.user_id');
$category = $this->get_child_categories($this->get_categories(), $matches[1]);
$this->db->where_in('artworks.category', $this->category['child']);
$this->db->group_by('artworks.id');
$query = $this->db->get();
return $query->result_array();
Second Query "get_categories()"
$this->db->select('*');
$this->db->order_by('parent', 'asc');
$this->db->order_by('name', 'asc');
$query = $this->db->get('categories');
return $query->result_array();
get_child_categories
function get_child_categories($categories, $parent){
foreach($categories as $category){
if($category['parent'] == $parent){
array_push($this->category['childs'], $category['id']);
$this->get_child_categories($categories, $category['id']);
}
}
}
But i'm getting this error where clearly displays that the second query is quetting inside the main one.
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM (`artworks`, `categories`) JOIN `users` ON `users`.`id` = `artworks`.`use' at line 1
SELECT `artworks`.*, `users`.`id` as user_id, `users`.`name` as user_name, * FROM (`artworks`, `categories`) JOIN `users` ON `users`.`id` = `artworks`.`user_id` WHERE `artworks`.`rating` IN ('g', 'm', 'a') ORDER BY `artworks`.`id` desc, `parent` asc, `name` asc
Filename: D:\Server\htdocs\gallery\system\database\DB_driver.php
Line Number: 330
I personally think this is an error in CodeIgniter's Active Record approach, if it's supposed to follow the Active Record pattern at all. It should totally enforce either one of these:
queries contained in a single data context
queries specified in a atomic instruction
As neither of these is happening, at the moment you're unwillingly mixing two queries with a structure that CodeIgniter does not support, thus creating that invalid query.
For a simple solution, I would suggest for you to invert the order of the instructions so that the queries are executed separately.
$category = $this->get_child_categories($this->get_categories(), $matches[1]);
# the first query gets executed here, your data context is cleaned up
$this->db->select('artworks.*, users.id as owner, users.name as user_name');
$this->db->from('artworks');
$this->db->join('users', 'users.id = artworks.user_id');
$this->db->where_in('artworks.category', $this->category['child']);
$this->db->group_by('artworks.id');
$query = $this->db->get();
# your second query gets executed here
return $query->result_array();