Mysql sub-query return null - mysql

Hi I am a beginner I am trying to make all the result row of my subquery that is null to return 0 not null. but I am getting an error. I will really appreciate any advice. Thank you
Error Code: 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 'AS 'Income'
SELECT
COUNT(DISTINCT t1.id) AS 'Val1',
COALESCE((SELECT SUM(CAST(COALESCE(r.t_payment_total,0) AS DECIMAL(18,2))) AS 'Income'
FROM reserv r
INNER JOIN newtbladds1 t ON t.t_parent_id = r.id
WHERE r.t_status!="Pending" && r.t_status!="Booked" AND r.c_mid = m.id AND t.t_type_id = t1.t_type_id
),0)AS 'Income'
FROM tbladds1 t1
JOIN tbladds1_type tt ON tt.id = t1.t_type_id
JOIN tbladdress m ON m.id = t1.t_mid
JOIN tbladdressfr mf ON mf.id = t1.t_floor_id
JOIN tblppl mp ON mp.t_mid = m.id AND mp.t_type = 'try' AND mp.t_system_id = 'ok'
GROUP BY t1.t_tool_type_id
ORDER BY m.t_m ASC, tt.t_ttype ASC, mf.t_floor ASC;
Output I removed COALESCE I am having null
Val1 Income
10 Null
2 30
23 10
5 Null
Desired Output
Val1 Income
10 0
2 30
23 10
5 0

I would suggest moving that subquery into the from clause
SELECT
t1.t_tool_type_id
, COUNT( DISTINCT t1.id ) AS `Val1`
, COALESCE(i.Income , 0 ) AS `Income`
FROM tbladds1 t1
JOIN tbladds1_type tt ON tt.id = t1.t_type_id
JOIN tbladdress m ON m.id = t1.t_mid
JOIN tbladdressfr mf ON mf.id = t1.t_floor_id
JOIN tblppl mp ON mp.t_mid = m.id
AND mp.t_type = 'try'
AND mp.t_system_id = 'ok'
left join (
SELECT
CAST( SUM(r.t_payment_total) AS decimal(18, 2) ) AS `Income`
FROM reserv r
INNER JOIN newtbladds1 t ON t.t_parent_id = r.id
WHERE r.t_status != 'Pending'
AND r.t_status != 'Booked'
AND r.c_mid = m.id
GROUP BY
t.t_type_id
) as i on t1.t_type_id = i.t_type_id
GROUP BY
t1.t_tool_type_id
;
nb: I have assumed r.t_payment_total is numeric.
I also suggest you always use single quotes for values/literals, and in MySQL backticks for identity (e.g. column headings) but really they are not essential in this query.

Related

mariadb access outer column in subquery

I have an issue with the following query that it is working on Mariadb 10.1.48 but it is not on 10.2.40.
It returns the following error
Error Code: 1054. Unknown column 'c.id' in 'where clause'
SELECT
p.id AS pid,
p.name AS pname,
c.id AS cid,
c.contract_code AS contr_code,
c.type AS ctype,
e.id AS eid,
e.state AS estate,
e.pay_code AS epay_code,
COUNT(z.id) AS damages,
rp.id AS resp_id,
rp.name AS resp_name,
rp.surname AS resp_surname,
IF(CURDATE() BETWEEN DATE_ADD(e.starts_pay_date, INTERVAL 23 DAY) AND DATE_ADD(e.starts_pay_date, INTERVAL 1 MONTH) AND e.state = 1, 1, 0) AS ending
FROM `contracts` AS c,
`customers` AS p,
`cash` AS e
LEFT JOIN `damage` z ON e.contract_id = z.contract_id AND z.state = 1
LEFT JOIN `customers` rp ON rp.id = (
SELECT MAX(p1.id) resp
FROM `customers` AS p1,
`contract_responsible` AS r
WHERE c.id = r.contract_id AND p1.id = r.resp_id )
WHERE e.starts_pay_date <= '2021-09-08 23:59:59' AND c.customer_id = p.id AND e.contract_id = c.id
GROUP BY e.id
ORDER BY e.inserted_date DESC
LIMIT 50 OFFSET 0
I know that it has to do with accessing outer column in a subquery, but I cannot understand why it used to work and now it is NOT!
Can you suggest a workaround?

Simplified SQL Query

Currently we have to run the following SQL Query to find all customers that have not been assigned access to a downloadable product.
SELECT c.entity_id as customer_id, dp.purchased_id as purchased_id
FROM magento_dev.sales_order as so
JOIN magento_dev.sales_order_address as soa on so.entity_id = soa.parent_id
JOIN magento_dev.customer_entity as c on c.email = soa.shipping_email
JOIN magento_dev.downloadable_link_purchased as dp on so.increment_id = dp.order_increment_id
where
so.customer_id = 12345 and
so.created_at > '2021-04-01' and
soa.shipping_email is not null and
dp.customer_id != c.entity_id
;
Which produces this:
customer_id purchased_id
99999 55555
Then with the results, we manually have to go through, and for each customer_id, and purchase_id run the following query:
UPDATE `magento_dev`.`downloadable_link_purchased` SET `customer_id` = '99999' WHERE (`purchased_id` = '55555');
So for the SQL Ninja's, any suggestions on how to make this a single query that finds the mismatched assignments and then does the update/insert at once?
Just put all the JOINs in the UPDATE query.
UPDATE `magento_dev`.`downloadable_link_purchased` AS dp1
JOIN magento_dev.sales_order as so
JOIN magento_dev.sales_order_address as soa on so.entity_id = soa.parent_id
JOIN magento_dev.customer_entity as c on c.email = soa.shipping_email
JOIN magento_dev.downloadable_link_purchased as dp
ON so.increment_id = dp.order_increment_id
AND dp.customer_id != c.entity_id
AND dp1.purchased_id = dp.purchased_id
SET dp1.customer_id = c.entity_id
where
so.customer_id = 12345 and
so.created_at > '2021-04-01' and
soa.shipping_email is not null
Can be done like sub query and join with the table which should be updated,
UPDATE
magento_dev.downloadable_link_purchased F
JOIN
(SELECT c.entity_id as customer_id, dp.purchased_id as purchased_id
FROM magento_dev.sales_order as so
JOIN magento_dev.sales_order_address as soa on so.entity_id = soa.parent_id
JOIN magento_dev.customer_entity as c on c.email = soa.shipping_email
JOIN magento_dev.downloadable_link_purchased as dp on so.increment_id = dp.order_increment_id
WHERE
so.customer_id = 12345 and
so.created_at > '2021-04-01' and
soa.shipping_email is not null and
dp.customer_id != c.entity_id) S
ON F.purchased_id = S.purchased_id
SET F.customer_id = S.customer_id;

Error related to only_full_group_by in MySql

I have created Query Which Gives error of only_full_group_by. I Want To change Query Not SET sql_mode=only_full_group_by
#1055 - Expression #4 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'hrdk.s.item_stock_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by#
This is the query that is giving me trouble:
SELECT `s`.`department_id`, `s`.`category_id`, `s`.`item_id`, `s`.`item_stock_id`, `s`.`tunch`, `cat`.`category_name`, `im`.`item_name`, `im`.`stock_method`, `cat`.`category_group_id`, SUM(s.grwt) AS grwt, SUM(s.ntwt) AS ntwt, sum(s.less) AS less, SUM(s.fine) AS fine
FROM `item_stock` `s`
LEFT JOIN `item_master` `im` ON `im`.`item_id` = `s`.`item_id`
LEFT JOIN `account` `pm` ON `pm`.`account_id` = `s`.`department_id`
LEFT JOIN `category` `cat` ON `cat`.`category_id` = `s`.`category_id`
WHERE (im.stock_method = 1 AND (`s`.`grwt` =0 OR `s`.`grwt` !=0)
OR (`im`.`stock_method` = 2 AND `s`.`grwt` != 0))
AND s.department_id IN(26,27,28,29,30,31,32,59)
AND `s`.`grwt` !=0
AND `s`.`department_id` = '26'
GROUP BY `s`.`category_id`, `s`.`item_id`, if(`im`.`stock_method` = 1, `s`.`tunch`, "")
ORDER BY `s`.`item_stock_id` DESC
Let me know if you need more information.
You've to add all non aggregated columns in group by
SELECT s.department_id, s.category_id, s.item_id, s.item_stock_id, s.tunch, cat.category_name, im.item_name, im.stock_method, cat.category_group_id, SUM(s.grwt) AS grwt, SUM(s.ntwt) AS ntwt, sum(s.less) AS less, SUM(s.fine) AS fine
FROM item_stock s LEFT JOIN item_master im ON im.item_id = s.item_id
LEFT JOIN account pm ON pm.account_id = s.department_id
LEFT JOIN category cat ON cat.category_id = s.category_id
WHERE (im.stock_method = 1 AND (s.grwt =0 OR s.grwt !=0) OR (im.stock_method = 2 AND s.grwt != 0))AND s.department_id IN(26,27,28,29,30,31,32,59) AND s.grwt !=0 AND s.department_id = '26'
GROUP BY s.department_id, s.category_id, s.item_id, s.item_stock_id, s.tunch, cat.category_name, im.item_name, im.stock_method, cat.category_group_id
ORDER BY s.item_stock_id DESC

Multiple-table UPDATE with WHERE not working

Can someone help me understand why below UPDATE query produces an ERROR?
WITH subt AS (
SELECT t.portfolio, s.isin, t.quantity, t.date
FROM transactions t
JOIN stocks s
ON t.stock = s.name
ORDER BY t.id DESC
LIMIT 1
)
UPDATE holdings h
JOIN subt
ON h.portfolio = subt.portfolio
AND h.isin = subt.isin
SET h.end_date = DATE_SUB(subt.date, INTERVAL 1 DAY)
WHERE h.end_date is NULL
The error I get:
SQL Error (1064): You have an error in your SQL syntax; check the
manual that corresponds to your MariaDB server version for the right
syntax to use near 'UPDATE holdings h JOIN subt ON h.portfolio =
subt.portfolio AND h.isin ' at line 10
While below SELECT works fine:
WITH subt AS (
SELECT t.portfolio, s.isin, t.quantity, t.date
FROM transactions t
JOIN stocks s
ON t.stock = s.name
ORDER BY t.id DESC
LIMIT 1
)
SELECT h.*
FROM holdings h
JOIN subt
ON h.portfolio = subt.portfolio
AND h.isin = subt.isin
WHERE h.end_date is NULL
I'm working with a MariaDB 10 Database via HeidiSQL
Instead of a WITH result you could try using a normal inner join on subquery
UPDATE holdings h
JOIN
(
SELECT t.portfolio, s.isin, t.quantity, t.date
FROM transactions t
JOIN stocks s
ON t.stock = s.name
ORDER BY t.id DESC
LIMIT 1
) subt
ON h.portfolio = subt.portfolio
AND h.isin = subt.isin
SET h.end_date = DATE_SUB(subt.date, INTERVAL 1 DAY)
WHERE h.end_date is NULL

Unknown column in on clause - in query converted from SQL to HQL

I'm using Hibernate 4.3.11 and MySQL 5.7.11.
I wanted to rewrite this MySQL query to HQL:
SELECT COALESCE(g1.id, g2.id) as id, COALESCE(g1.type, g2.type) as type, COALESCE(g1.email_id, g2.email_id) as email_id, COALESCE(g1.url_id, g2.url_id) as url_id FROM notifications n
LEFT JOIN emails ON emails.id = n.email_id
LEFT JOIN urls ON urls.id = n.url_id
LEFT JOIN notifications_group g1 ON g1.email_id = n.email_id
LEFT JOIN notifications_group g2 ON g2.url_id = n.url_id
WHERE (((n.type = 'EMAIL' OR n.type = 'REMINDER') AND n.email_id is not null AND emails.user_id = :userId)
OR (n.type = 'URL' AND n.url_id is not null AND urls.user_id = :userId))
AND (g1.id is not null OR g2.id is not null)
AND ((g1.id is not null AND g1.id < :beforeId) OR (g2.id is not null AND g2.id < :beforeId))
GROUP BY COALESCE(g1.id, g2.id)
ORDER BY MAX(n.id) DESC
I have rewritten this native query to HQL:
SELECT COALESCE(g1.id, g2.id), COALESCE(g1.type, g2.type), COALESCE(g1.email, g2.email), COALESCE(g1.url, g2.url) FROM Notification n
LEFT JOIN n.email e
LEFT JOIN n.url u
LEFT JOIN e.notificationGroup g1
LEFT JOIN u.notificationGroup g2
WHERE (((n.type = delimail.enums.NotificationType.EMAIL OR n.type = delimail.enums.NotificationType.REMINDER) AND e IS NOT NULL AND e.user = :user)
OR (n.type = delimail.enums.NotificationType.URL AND u IS NOT NULL AND u.user = :user))
AND (g1 IS NOT NULL OR g2 IS NOT NULL)
AND ((g1.id IS NOT NULL AND g1.id < :beforeId) OR (g2 IS NOT NULL AND g2.id < :beforeId))
GROUP BY COALESCE(g1.id, g2.id), COALESCE(g1.type, g2.type), COALESCE(g1.email, g2.email), COALESCE(g1.url, g2.url)
ORDER BY MAX(n.id)
But it don't work. Hibernate generates this query:
SELECT coalesce(notificati3_.id, notificati4_.id) AS col_0_0_,
coalesce(notificati3_.type, notificati4_.type) AS col_1_0_,
coalesce(notificati3_.email_id, notificati4_.email_id) AS col_2_0_,
coalesce(notificati3_.url_id, notificati4_.url_id) AS col_3_0_
FROM delimail.notifications notificati0_
LEFT OUTER JOIN delimail.emails email1_ ON notificati0_.email_id=email1_.id
LEFT OUTER JOIN delimail.notifications_group notificati3_ ON email1_.id=notificati3_.email_id,
delimail.emails email5_, --l 8
delimail.urls url7_ --l 9
LEFT OUTER JOIN delimail.urls url2_ ON notificati0_.url_id=url2_.id --error: Unknown column 'notificati0_.url_id' in 'on clause'
LEFT OUTER JOIN delimail.notifications_group notificati4_ ON url2_.id=notificati4_.url_id,
delimail.emails email6_, --l 12
delimail.urls url8_ --l 13
WHERE notificati3_.email_id=email5_.id --l 14
AND notificati3_.url_id=url7_.id --l 15
AND notificati4_.email_id=email6_.id --l 16
AND notificati4_.url_id=url8_.id --l 17
AND ((notificati0_.type='EMAIL'
OR notificati0_.type='REMINDER')
AND (email1_.id IS NOT NULL)
AND email1_.user_id=?
OR notificati0_.type='URL'
AND (url2_.id IS NOT NULL)
AND url2_.user_id=?)
AND (notificati3_.id IS NOT NULL
OR notificati4_.id IS NOT NULL)
AND ((notificati3_.id IS NOT NULL)
AND notificati3_.id<?
OR (notificati4_.id IS NOT NULL)
AND notificati4_.id<?)
GROUP BY coalesce(notificati3_.id, notificati4_.id),
coalesce(notificati3_.type, notificati4_.type),
coalesce(notificati3_.email_id, notificati4_.email_id),
coalesce(notificati3_.url_id, notificati4_.url_id)
ORDER BY MAX(notificati0_.id)
And the error is:
Unknown column 'notificati0_.url_id' in 'on clause'
SQL Warning Code: 1054, SQLState: 42S22
But this query works as expected after removing marked lines 8-9, 12-13, and removing conditions in lines 14-17.
How can I convert this query to HQL? If it's possible.
I guess in this case since the query is kind of complex, You can very well go for native Query
Please see sample below:
String q="select employee_name from employee";
Query query= em.createNativeQuery(q,Object[].class);
List<Object[]> students= query.getResultList();
Please refer to the documentation below :
http://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#createNativeQuery-java.lang.String-