Convert a query from SQL to CodeIgniter - sql

This is the query I need to convert from SQL to CodeIgniter:
select *, count(username) as totalattempt from (select * from my_table order by created desc) as created2 group by `username` order by created desc
I've tried searching on Active Record CodeIgniter, but failed to get an answer.
Thanks.

Codeigniter didn’t provided any option to use sub queries with active record class.
Try:
$this->db->select('*')->from('my_table')->order_by('created','DESC');
$subQuery = $this->db->get_compiled_select();
/* Main Query */
$result = $this->db->select('created2.*, count(created2.username) as totalattempt')
->from('('.$subQuery.') as created2')
->group_by('created2.created','DESC')
->order_by('created2.username')
->get()
->result_array();
Thanks!

Related

SQL Many-to-Many Query in Apex Oracle

I created a many-to-many relationship between the tables PRODUCT_TYPE and LABEL by creating and intermediate table PRODUCT_TYPE-LABELS. I wanted to retrieve all the products that have the labels 'Gluten free' and 'Lactose free' and found help on a similar subject (How to filter SQL results in a has-many-through relation) but never got it to work properly.
The tables are as follows:
PRODUCT_TYPE{
PRODUCT_TYPE ->Primary Key
CONTAINER
VOLUME_L
PRICE_EUROS
...
}
LABEL{
LABEL_NAME ->Primary Key
REQUIREMENTS
}
PRODUCT_TYPE-LABELS{
PRODUCT_TYPE
LABEL_NAME
}
In fact, even when creating the simplest command
SELECT PRODUCT_TYPE-LABELS.PRODUCT_TYPE
FROM PRODUCT_TYPE-LABELS
I obtain the following error ORA-00933: SQL command not properly ended that I can't solve. I'm working on Apex Oracle (Required for this course).
Thanks !
If your table is really named PRODUCT_TYPE-LABELS then you need to enclose it within double quotes. - is not a standard character that is allowed in table names so to use special characters such as that, you need to put quotes around the table. I would recommend AGAINST using a table name such as that and maybe use something like PRODUCT_TYPE_LABEL.
Does the query work from SQL Developer, SQLPlus or any other tool that you can use to run queries?
Try running the query:
SELECT PRODUCT_TYPE
FROM "PRODUCT_TYPE-LABELS"
select * from (
select rownum rowno, CUST_ID,CUST_NAME,no_of_orders,orders_amount,EMAIL from (
select mst.CUST_ID, mst.CUST_NAME, count(mst.INVONO) no_of_orders, sum(SUB_TOTAL) orders_amount, au.EMAIL
from sales_mst mst,CUSTOMER_INFO cust, APP_USERS au
where cust.USER_NAME = au.USERNAME
and cust.cust_id=mst.cust_id
and (au.gender= :P41_GENDER or :P41_GENDER is null)
and (au.DOB = :P41_DOB or :P41_DOB is null)
group by mst.CUST_ID, mst.CUST_NAME,au.EMAIL
having nvl(sum(SUB_TOTAL),0) > 0
order by 3 desc,4 desc
)) where rowno <=:P41_TO_CUSTOMER
/*select * from (
select rownum rowno, CUST_ID,CUST_NAME,no_of_orders,orders_amount from (
select mst.CUST_ID, mst.CUST_NAME, count(mst.INVONO) no_of_orders, sum(SUB_TOTAL) orders_amount
from sales_mst mst
group by mst.CUST_ID, mst.CUST_NAME
having nvl(sum(SUB_TOTAL),0) > 0
order by 3 desc,4 desc
)) where rowno <=:P41_TO_CUSTOMER
*/

Laravel raw query: total with select inside count

I'm building a SQL query (Postgres is it matters), that will return me the list of articles with all the fields and with total number of references.
$a = Articles::select(DB::raw('
*,
count(
select * from "references"
where exists (select * from "users" where "users"."reference_id" = "references"."id"
and "article_id" = ?????
) as total'
))->where('created_at', '<', $date)->get();
I simplified it a little bit; there more 'exists' conditions inside the count(); there is also more ->where() rules that are dynamic and hard to rewrite in raw SQL. My main misunderstanding is how to put the corresponding article_id instead of ?????. Could someone give me a hint.
Try this its about binding parameter to Raw query.
https://laracasts.com/discuss/channels/laravel/how-to-bind-parameters-to-a-raw-query?page=1
You may pass in the parameters to be bound to the raw select using a PHP array:
$a = Articles::select(DB::raw('
*,
count(
select * from references r
where exists (select 1 from users u
where u.reference_id = r.id and article_id = ?)
) as total', ['some id here']))
->where('created_at', '<', $date)
->get();
There may be a better way to write your query in Postgres. If you can add some sample data, maybe more can be said about that.

Yii2: How to convert query with subquery to Actived Record?

I want to convert this very simple SQL query with a subquery to Yii Active Record (I am using PostgreSQL).
SELECT
totals.name,
FROM (
SELECT
products.id,
products.name
FROM "products"
) AS totals
How can I convert it to Active Record?
I found this question but it's not exactly what I need.
In general, you can use findBySql() ActiveRecord static method.
$subquery = (new \yii\db\Query)->from('products')->select(['id','name']);
$query = (new \yii\db\Query)->from(['totals' => $subquery])->select('name');
$items = Model::findBySql($query->createCommand()->getRawSql())->all();

PostgreSQL Select where multiple OR statements

I have the following PgSQL query, in which i'm looking where user_id equals any one of a set of id's i am looking for.
Question is, is there a way to simply the statement so that I dont have to keep putting user_id= ?
SELECT *
FROM comments
WHERE session_id=1
AND (user_id=10 OR user_id=11
OR user_id=12 OR user_id=13
OR user_id=14 OR user_id=15
OR user_id=16)
SELECT *
FROM comments
WHERE session_id=1
AND user_id in (10,11,12,13,14,15,16);
alternatively for this specific case:
SELECT *
FROM comments
WHERE session_id=1
AND user_id between 10 and 16;

SQL get distinct values but showing all rows with Symfony Doctrine

I have a table like :
a.id; a.username; a.mail; a.optin
Considering theses values :
1; tobby; tobby#google.com; true
2; franck; tobby#google.com; true
3; john; john#google.com; true
I would like (in SQL, but also in Symfony with Doctrine) to get ALL values and ALL rows (id, username, mail, optin) BUT Distinct by email.
With SELECT DISTINCT mail, I only have mails....
Could you help me please ? Thanks !
$qb = $em->getRepository('Your Entity here')->createQueryBuilder('a')->groupBy('a.mail');
$result = $qb->getQuery()->getResult();
Here's more explanation:
The first line builds your query with a select all columns of the entity you fill in and the groupBy will give you distinct rows by email.
In MySql the query generated from this is equivalent to:
SELECT *
FROM 'Your Entity here'
GROUP BY mail