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);
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'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;
I'm writing an archival function in a Laravel site and I can't figure out how to replicate this query using Laravel's query builder. My databases are 'archive' and 'live'.
INSERT INTO archive.daily_by_post
SELECT post_date, user_id, post_id
FROM live.clicks
WHERE timestamp BETWEEN '2014-07-28 00:00:00' AND '2014-07-28 23:59:59'
GROUP BY user_id, post_id;
Should I use a different method? Is this even possible?
It is possible of course.
However you need to build your query either using raw statement OR Connection::insert() mixed with Query\Builder like below:
$from = '2014-07-30 00:00:00';
$till = '2014-07-30 23:59:59';
$select = DB::table('live.clicks')
->select('post_date', 'user_id', 'post_id')
->whereBetween('updated_at', [$from, $till]) // empty array will do
->groupBy('user_id', 'post_id');
$statement = 'INSERT INTO archive.daily_by_post (specify fields if necessary) '
. $select->toSql();
DB::insert($statement, $select->getBindings());
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.
How do I select multiple rows from SQL?
ie. $results->row(1,2,3,4,5,10)
Are you using ActiveRecord? If so, you can use the where_in() method when making your query. It's not something you do after the query is finished, as you seem to be doing in your example.
$this->db->where_in('id', array(1,2,3,4,5,10));
$query = $this->db->get('myTable');
// This produces the query SELECT * FROM `myTable` WHERE `id` IN (1,2,3,4,5,10)
See the this CodeIgniter docs section for more info on SELECT statement support.