Yii CDbCriteria add column - mysql

I created a criteria:
$ids = array(1,2,3);
$criteria = new CDbCriteria;
$criteria->select = 'SUM(quantity) as quan';
$criteria->with = array('order');
$criteria->condition="order.customer = ".Yii::app()->user->id." AND order.status_id <> 4 AND order.status_id <> 3 AND order.type = 0";
$criteria->addInCondition("product_id", $ids);
$order_prod = OrderProduct::model()->find($criteria);
but when i run this i got error:
1140 In aggregated query without GROUP BY, expression #2 of SELECT list contains nonaggregated column 'als.t.id'; this is incompatible with sql_mode=only_full_group_by. The SQL statement executed was: SELECT SUM(quantity) as quan, t.id AS t0_c0, order.id AS t1_c0, order.phone AS t1_c1, order.email AS t1_c2.
In criteria select i use only sum of quantity.

Hi Disable only_full_group_by
try this sql
SET GLOBAL sql_mode=(SELECT REPLACE(##sql_mode,'ONLY_FULL_GROUP_BY',''));

You want to get only quantity sum from OrderProduct table. So, it'll be better not to use active record, but write simple command with query, something like this:
$result = Yii::app()->db->createCommand('
SELECT SUM(t.quantity) as quan
FROM order_product t
LEFT JOIN order ON order.ID = t.order_id
WHERE
order.customer = :userId AND
order.status_id NOT IN (3,4) AND
order.type = 0 AND
t.product_id IN (1,2,3)
')->queryScalar([
':userId' => Yii::app()->user->id,
]);
Here "db" is the name of your CDbConnection component. OrderProduct table name and join condition may be different in your system.

Related

How to use 'Mysql JOIN' with sql text of same table

I want to use mysql's "JOIN"
I want to group rows by "date_text" where "tokenIdx" is "1001" and "datetime_unix" is the highest value.
Is my code wrong?
SELECT `A.idx`
FROM `data_candle_h1` 'A'
JOIN
(
SELECT `date_text`, MAX(`datetime_unix`) AS 'datetime_unix'
FROM `data_candle_h1`
WHERE `tokenIdx` = '1002'
GROUP BY `date_text`
) 'B'
ON `A.datetime_unix` = `B.datetime_unix`
WHERE `A.tokenIdx` = '1002'
Your query is syntactically perfect. Just remove single quotes('') around table aliases (A and B). I have corrected it. Please check this out.
SELECT `A.idx`
FROM `data_candle_h1` A
JOIN
(
SELECT `date_text`, MAX(`datetime_unix`) AS 'datetime_unix'
FROM `data_candle_h1`
WHERE `tokenIdx` = '1002'
GROUP BY `date_text`
) B
ON `A.datetime_unix` = `B.datetime_unix`
WHERE `A.tokenIdx` = '1002'

MySQL: Invalid use of group function updating two columns with update/select

I am trying to update two columns within a table from a select statment in MySQL 5.7.
The error I get is "invalid use of group function"
Stmt:
UPDATE
catalog mpc
JOIN
reviews mpr ON mpr.merchant_id = mpc.MERCHANT_ID and mpr.sku = mpc.ARTICLE_ID
SET
mpc.RATING = avg(mpr.rating),
mpc.RATINGS = count(mpr.rating)
WHERE
mpr.MERCHANT_ID = 1
AND mpr.sku = '133';
It looks about right to me, what could be the problem here?
You must aggregate first in reviews and then join to catalog:
UPDATE catalog mpc
INNER JOIN (
SELECT merchant_id, sku, AVG(rating) avg_rating, COUNT(rating) count_rating
FROM reviews
WHERE merchant_id = 1 AND sku = '133'
GROUP BY merchant_id, sku
) mpr ON mpr.merchant_id = mpc.MERCHANT_ID and mpr.sku = mpc.ARTICLE_ID
SET mpc.RATING = mpr.avg_rating,
mpc.RATINGS = mpr.count_rating

Zf2 table gateway join query to fetch only the latest row(by id) from second table

Hi, I need a zf2 join query that fetches only the latest row(by id DESC) from the second table. I have written an sql query and it works.
SELECT st1.customer_id,
st1.id
FROM status st1
inner JOIN
(
SELECT max(id) MaxId, customer_id
FROM status
GROUP BY customer_id
) st2
ON st1.customer_id = st2.customer_id
AND st1.id = st2.MaxId
But I need this query at zend framework 2 table gateway format. Please help.
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Expression;
$sql = new Select ();
$sql->columns(["customer_id", new Expression ("max(id) AS MaxId")])
->from ('status')
->group('customer_id');
$outer = new Select ();
$outer->columns (['customer_id', 'id'])
->from (['st1' => 'status'])
->join (['st2' => $sql],
'st1.customer_id = st2.customer_id AND st1.id = st2.MaxId', []);

issues in table alias in codeigniter

Here, I am creating an alias for the inner selection, but it automatically adds the table prefix to the alias table. My sql query is as follows:
SELECT
`tb1`.*, `tb2`.*, `tb3`.`client_name`,
`cms_tb4`.*, `tb1`.`project_status` AS pstat
FROM
(`cms_projects` tb1)
JOIN `cms_project_type` tb2 ON `tb2`.`id` = `tb1`.`project_type`
JOIN `cms_clients` tb3 ON `tb1`.`client_id` = `tb3`.`client_id`
JOIN (
SELECT
*
FROM
(
SELECT
t1.project_id AS projid,
t2.work_id,
t2.work_date
FROM
cms_projects_mod t1,
cms_work_status_emp t2
WHERE
t1.module_id = t2.pro_module_id
ORDER BY
t2.work_date DESC
) AS subtb4
GROUP BY
projid
ORDER BY
work_date DESC
) AS tb4 ON `cms_tb4`.`projid` = `tb1`.`project_id`
LIMIT 50
i am working on codeigniter framework.
in codeigniter model just like this
$this->db->select('tb1.*');
$this->db->select('tb1.project_status as pstat');
$this->db->from('cms_projects tb1');
$this->db->join('project_type tb2', 'tb2.id=tb1.project_type');
$this->db->join('clients tb3', 'tb1.client_id = tb3.client_id');
$this->db->join("(
select * from (
select t1.project_id as projid, t2.work_id,t2.work_date from cms_projects_mod t1, cms_work_status_emp t2 where t1.module_id = t2.pro_module_id order by t2.work_date desc) as subtb4
group by projid order by work_date desc ) as tb4 ",
"tb4.projid = tb1.project_id" ,false);
$this->db->group_by("tb1.project_id");
$this->db->order_by("tb3.work_date",'desc');
here i didn't give any prefix in third join tb4 but CI Add automatically when the running time.
Please check the code order in CodeIgniter Documentation.
$this->db
->select()
->from()
->join()
This is the correct order. Changing the order sometimes causes issues in complex queries.
Visit this link https://github.com/bcit-ci/CodeIgniter/issues/2975
Why you using query strings? If you using coeignoter why dont you use active record. Active Record queries are automatically protected with sql injection.
you can do kind of this....its not same you want just idea how you can use active record sql.
$query = $this->db->select('*',FALSE)
->from('tb1','tb2'.....)
->join('tb2', 'tb1.cms_project_type = tb2.cms_project_type','left')
->join('tb3', 'tb1.cms_project_type = tb2.cms_project_type','left')
->group_by('projid')
->order_by('work_date','DESC')
->get();
https://ellislab.com/codeigniter/user-guide/database/queries.html
Hope this help.

How to write a relatively simple UPDATE query with two linked tables

I have 2 tables, CARS and ORDERS.
Both have a mileage column, but the ORDERS table mileage column is blank on most rows.
I'd like to update the ORDERS.mileage with CARS.mileage. They are linked by a Vrm column.
Can someone help me with this query?
UPDATE orders
SET Mileage = (SELECT *
FROM `orders`
JOIN cars ON orders.Vrm = cars.Vrm
WHERE orders.mileage = '')
Use a JOIN in the UPDATE's FROM clause, rather than trying to use a subquery. Otherwise, you basically have the right idea.
UDPATE
orders
JOIN CARS ON orders.Vrm = cars.VRM
SET orders.Mileage = cars.mileage
WHERE orders.mileage = ''
Query 1:
UPDATE orders
SET Mileage = (SELECT c.mileage
FROM cars c
WHERE orders.Vrm = c.Vrm)
WHERE o.mileage = ''
Query 2:
UPDATE orders o
JOIN cars c ON o.Vrm = c.Vrm
SET o.Mileage = c.mileage
WHERE o.mileage = ''
Some sqlfidleexample
According MySQL documentation, you should use this:
UPDATE orders, cars
SET orders.Mileage = cars.mileage
WHERE orders.Vrm = cars.Vrm AND orders.mileage = ''