"SELECT ... IN (SELECT ...)" query in CodeIgniter - codeigniter

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.

Related

How do I print the values as well as count in Thymeleaf from a JPA custom query?

#Query(value = "select p.*, count(c.post_id) from posts as p join comments as c on p.id = c.post_id group by c.post_id order by p.id desc", nativeQuery = true)
List<Post> findAllAndCountResponsesOrderByPostIdDesc();
I have this as my custom query in my repository. I know the SQL works because I tested in out in MySQL, but I just can't seem to print it out in my Thymeleaf template. In my controller, I've added a model attribute, 'posts' for example, and if I call all of the table columns, it works (post.title, post.body, etc...), but when I try to print out the count (post.count), it breaks. What would I need to put to print it out?
Thank you in advance!

How to run sql query stored in a variable with Laravel Eloquent?

I want to run a sql query that I store in a variable in Laravel. It's really easy to do in CodeIgniter with just running $this->db->sql($sql). I wonder if there is a way like this in Laravel.
$sql = "SELECT u.*,c.city_name,prov.province_name FROM users u ".
"LEFT JOIN cities c ON c.city_id=u.city_id".
"LEFT JOIN provinces prov ON prov.province_id=u.province_id".
"WHERE u.id= ?";
I tried to execute it using DB::table($sql) but I guess that's not the way.
EDIT:
Using the following is working fine but I still wonder if I just can run something like I do in CI with running $this->db->query($sql).
$user = User::select('users.*','cities.city_name','provinces.province_name')
->where('users.id', Auth::id())
->leftJoin('cities','cities.city_id','=','users.city_id')
->leftJoin('provinces','provinces.province_id','=','users.province_id')
->get()->first();
you can use this
$users = DB::select('select * from users where active = ?', [1]);
refer the docs https://laravel.com/docs/5.7/database#running-queries
so if you
$sql = "SELECT u.*,c.city_name,prov.province_name FROM users u ".
"LEFT JOIN cities c ON c.city_id=u.city_id".
"LEFT JOIN provinces prov ON prov.province_id=u.province_id".
"WHERE u.id= ?";
just try
$query_result = DB::select($sql, [your parameter variable]);
Create eloquent relationships in models. When there is a relationship between models, you do not have to create a long sql query. You can refer to their documentation. It is really easy to understand.
https://laravel.com/docs/5.6/eloquent-relationships
Try this:
$rows = DB::select(
DB::raw($sql, array($stringids))
);

Interleaving the rows of two different SQL tables, group by one row

My Sql query is like this
$view = mysql_query ("SELECT domain,count(distinct session_id) as
views FROM `statistik` left join statistik_strippeddomains on
statistik_strippeddomains.id = statistik.strippeddomain WHERE
`angebote_id` = '".(int)$_GET['id']."' and strippeddomain!=1
group by domain having count (distinct session_id) >
".(int)($film_daten['angebote_views']/100)." order
count(distinct session_id$vladd) desc limit 25");
How can I write its Codeigniter Model I appreciate any Help
try this
$this->db->select('statistik.domain,statistik.count(DISTINCT(session_id)) as views');
$this->db->from('statistik');
$this->db->join('statistik_strippeddomains', 'statistik_strippeddomains.id = statistik.strippeddomain', 'left');
$this->db->where('angebote_id',$_GET['id']);
$this->db->where('strippeddomain !=',1);
$this->db->group_by('domain');
$this->db->having('count > '.$film_daten['angebote_views']/100, NULL, FALSE);
$this->db->order_by('count','desc');
$this->db->limit('25');
$query = $this->db->get();
Comment me If you have any query.

How we can write multiple select keyword in a single mysql query using Magento?

here is my query and this give proper ouput.
But How can I set it according to magento rules?
SELECT main_table.*,
(select company from sales_flat_order_address sfoa where sfoa.entity_id=sfo.billing_address_id) as bill_to_company,
(select company from sales_flat_order_address sfoa where sfoa.entity_id=sfo.shipping_address_id) as ship_to_company
FROM sales_flat_order_grid as main_table inner join sales_flat_order as sfo
on main_table.entity_id = sfo.entity_id
please help me....
Thanks & Reagards
Praful
You can use magento default connection Model
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$result=$write->query("your query as like mysql query no different");
$row = $readresult->fetch(); // this will fetch all your data

Using Mysql WHERE IN clause in codeigniter

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);

Resources