Subquery is not identifying column of main query - mysql

Error is
"Error in query (1054): Unknown column 'nt.id' in 'where clause'"
This the query
SELECT
nt.from as 'SENDER EMP ID',
if(nt.notification_time IS NOT NULL, nt.notification_time, nt.notification_start_time) as 'NOTIFICATION TIME',
nt.delivery_type as 'NOTIFICATION TYPE',
eh.first_name as 'SENDER FIRST NAME',
eh.last_name as 'SENDER LAST NAME',
eh.site_name as 'SENDER SITE NAME',
nt.title as 'NOTIFICATION TITLE',
nt.body as 'NOTIFICATION BODY',
(
select count(DISTINCT notifiable_id)
from notifications.notifications
where nt.id = notifications.notification_template_id
) as SEND TO No. OF USERS,
(
select GROUP_CONCAT('\n', counts_per_desig ) as counts
from
(
select
concat (if(quartz.employee_hierarchy.designation, quartz.employee_hierarchy.designation, "Un Assigned"), " : ", count(*) ) as counts_per_desig
from notifications.notifications
LEFT JOIN quartz.employee_hierarchy ON quartz.employee_hierarchy.employee_id = notifications.notifications.notifiable_id
where notifications.notifications.notification_template_id = nt.id
AND notifications.read_at IS NOT NULL
Group By quartz.employee_hierarchy.designation
) as 'READ BY No. OF USERS'
)
FROM notifications.notification_template AS nt
LEFT JOIN quartz.employee_hierarchy as eh ON eh.employee_id = nt.from
where (nt.created_by_type = 1)
and eh.location_id in (22, 123, 332)
and nt.from not in (185994, 81016, 168090, 24799, 104967)
There is a problem in this portion so code (subquery)
select GROUP_CONCAT('\n',counts_per_desig ) as counts
from
(
select concat (if(quartz.employee_hierarchy.designation,quartz.employee_hierarchy.designation,"Un Assigned")," : ",count(*) ) as counts_per_desig
from notifications.notifications
LEFT JOIN quartz.employee_hierarchy ON quartz.employee_hierarchy.employee_id = notifications.notifications.notifiable_id
where notifications.notifications.notification_template_id = 123
AND notifications.read_at IS NOT NULL
Group By quartz.employee_hierarchy.designation
) as 'READ BY No. OF USERS'

Your problem is that you are one level too deep. Unfortunately it is not possible to access a column name in a sub sub query.
You must hence move the join criteria (the notification template ID) one level up. Change:
(
select GROUP_CONCAT('\n', counts_per_desig ) as counts
from
(
select
concat (if(quartz.employee_hierarchy.designation, quartz.employee_hierarchy.designation, "Un Assigned"), " : ", count(*) ) as counts_per_desig
from notifications.notifications
LEFT JOIN quartz.employee_hierarchy ON quartz.employee_hierarchy.employee_id = notifications.notifications.notifiable_id
where notifications.notifications.notification_template_id = nt.id
AND notifications.read_at IS NOT NULL
Group By quartz.employee_hierarchy.designation
) as 'READ BY No. OF USERS'
)
to
(
select group_concat('\n', counts_per_desig)
from
(
select
n.notification_template_id,
concat(coalesce(ne.designation, 'unassigned'), ' : ', count(*)) as counts_per_desig
from notifications.notifications n
left join quartz.employee_hierarchy ne on ne.employee_id = n.notifiable_id
where n.read_at is not null
group by n.notification_template_id, ne.designation
) designations
where designations.notification_template_id = nt.id
) as read_by_no_of_users

Related

**Unknown column 'timeStamp' in 'field list'**

I'm getting this error, I am new to sql I don't get any solution regarding my problem, I would really Appreciate if someone can help get me rid of this error
SELECT job.jobStatusId,
job.customerId,
mazdoor.mazdoorName,
mazdoor.picture ,
job.mazdoorId,
job.workingHistoryId,
service.serviceName,
service.price ,
contractor.cnic ,
contractor.contractorId,
contractor.contractorName ,
SUM(CONCAT(Extract(HOUR From timeStamp) ,'.', Extract(MINUTE From timeStamp))*service.price*0.05 ) AS GRANDTOTAL ,
Date(job.timesStamp) AS Date
FROM job
INNER JOIN mazdoor ON mazdoor.mazdoorId = job.mazdoorId
INNER JOIN service ON service.serviceId = job.serviceId
INNER JOIN contractor ON mazdoor.contractorId = contractor.contractorId
WHERE job.jobStatusId = '3'
AND mazdoor.jobsCompleted>=1
AND mazdoor.contractorId = '$email'
GROUP BY contractor.cnic
--The column was misspelled
SELECT job.jobStatusId,
job.customerId,
mazdoor.mazdoorName,
mazdoor.picture ,
job.mazdoorId,
job.workingHistoryId,
service.serviceName,
service.price ,
contractor.cnic ,
contractor.contractorId,
contractor.contractorName ,
SUM(CONCAT(Extract(HOUR From timeStamp) ,'.', Extract(MINUTE From timeStamp))*service.price*0.05 ) AS GRANDTOTAL ,
Date(job.timeStamp) AS Date --< column name was wrong.
FROM job
INNER JOIN mazdoor ON mazdoor.mazdoorId = job.mazdoorId
INNER JOIN service ON service.serviceId = job.serviceId
INNER JOIN contractor ON mazdoor.contractorId = contractor.contractorId
WHERE job.jobStatusId = '3'
AND mazdoor.jobsCompleted>=1
AND mazdoor.contractorId = '$email'
GROUP BY job.jobStatusId,
job.customerId,
mazdoor.mazdoorName,
mazdoor.picture ,
job.mazdoorId,
job.workingHistoryId,
service.serviceName,
service.price ,
contractor.cnic ,
contractor.contractorId,
contractor.contractorName ,
Date(job.timeStamp)
`
-- and the non-aggregate fields has to be group by

Maria DB SQL Code and Stored Procedure giving different Output

SQL Code is mentioned here , please have a look at this.
SELECT concat('{"workbenchStatsByUser": [', GROUP_CONCAT(js SEPARATOR ','))
FROM
(
SELECT json_object('username', workbenchStatsByUser, 'workbenchStatsByStatus',
JSON_ARRAY(GROUP_CONCAT( json_object( 'status', TempStatus, 'count', IFNULL(count, 0) ) SEPARATOR ','))) AS Js
FROM
(
SELECT
CASE WHEN username IS NULL THEN 'Not Assigned'
ELSE CONCAT(username,' - ', rolename)
END AS workbenchStatsByUser,
TempStatus,
COUNT(TempStatus) AS count
FROM users u
INNER JOIN tempOrgId t ON u.OrgId = t.OrgId
CROSS JOIN TempStatus ts
LEFT JOIN roles r ON r.id = u.roleid
LEFT JOIN vtask vt ON u.username = vt.updatedby AND ts.TempStatus = vt.status
GROUP BY workbenchStatsByUser, TempStatus
) A
GROUP BY workbenchStatsByUser
) B;
Username is null even-though their is a proper value.
Try changing
CASE WHEN username IS NULL THEN 'Not Assigned'
ELSE CONCAT(username,' - ', rolename)
END AS workbenchStatsByUser,
to
COALESCE(CONCAT(username,' - ', rolename), 'Not Assigned') AS workbenchStatsByUser,

mySQL Exclude entire result if GROUP_CONCAT returns NULL

If this is a dupe, I apologize. I couldn't find it.
I have this convoluted query that hits 3 tables, and I need to figure out how to exclude an entire result if the GROUP_CONCAT as shows returns NULL (which it does often). To clarify, if shows comes up NULL, then I don't want any of the profile data for that result either. I want the entire row skipped.
SELECT
`profiles`.*,
IF( `profiles`.`profile_id` IN(
SELECT DISTINCT (`badges`.`profile_id`)
FROM `badges`
), TRUE, FALSE ) AS `has_registrations`,
(SELECT
GROUP_CONCAT( DISTINCT `shows`.`show_name` SEPARATOR '<br>' )
FROM `shows`
LEFT JOIN `badges` ON `badges`.`show_id` = `shows`.`show_id`
WHERE
`badges`.`profile_id` = `profiles`.`profile_id`
AND `shows`.`end_date` >= CURDATE()
) AS `shows`
FROM `profiles`
Also accepting input on speed/elegance of the overall query.
Probably there is a more efficient way to do this but I think a simple where clause will do the trick.
SELECT
`profiles`.*,
IF( `profiles`.`profile_id` IN(
SELECT DISTINCT (`badges`.`profile_id`)
FROM `badges`
), TRUE, FALSE ) AS `has_registrations`,
(SELECT
GROUP_CONCAT( DISTINCT `shows`.`show_name` SEPARATOR '<br>' )
FROM `shows`
LEFT JOIN `badges` ON `badges`.`show_id` = `shows`.`show_id`
WHERE
`badges`.`profile_id` = `profiles`.`profile_id`
AND `shows`.`end_date` >= CURDATE()
) AS `shows`
FROM `profiles`
where `shows` IS NOT NULL
You could add a having clause:
SELECT
`profiles`.*,
IF( `profiles`.`profile_id` IN(
SELECT DISTINCT (`badges`.`profile_id`)
FROM `badges`
), TRUE, FALSE ) AS `has_registrations`,
(SELECT
GROUP_CONCAT( DISTINCT `shows`.`show_name` SEPARATOR '<br>' )
FROM `shows`
LEFT JOIN `badges` ON `badges`.`show_id` = `shows`.`show_id`
WHERE
`badges`.`profile_id` = `profiles`.`profile_id`
AND `shows`.`end_date` >= CURDATE()
) AS `shows`
FROM `profiles`
having shows is not null
If i understand questions correctly, you don't need null values. Perhaps the null value occurs due use of left join why don't you try with inner join their will be no null values.

Simplyfy the mysql query for the insert

I am working on creating a new query for inserting values in to a table which pulls values from the other table
INSERT INTO user (EmailAddress, InternalPhone, ExternalPhone, CreatedBy, DateCreated,roll_key,user_key )
VALUES ( NULL, NULL, NULL, 1, 'dba', Now(),
(select r.roll_key from user u
join work wrk on u.work_key = wrk.Work_key
join roll r on r.Name = 'Ext'
where u.Name = 'test'),
(select u.user_key from user u
join work wrk on u.work_key = wrk.Work_key
join roll r on r.Name = 'Ext'
where u.Name = 'test'))
How can I simply this query instead of having the select statements in to the values.
You could use a single select and assign the fixed value to pseudo column
INSERT INTO user (EmailAddress, InternalPhone, ExternalPhone, CreatedBy, DateCreated,roll_key,user_key )
select NULL, NULL, 1, 'dba', Now(), r.roll_key, u.user_key
from user u
join work wrk on u.work_key = wrk.Work_key
join roll r on r.Name = 'Ext'
where u.Name = 'test'

optimizing a union join inside select statement of other joins

I have a query I built in 3 -4 parts. This takes over 140secs to run once I add the union join with join. How can I change the union join to execute it faster.
SELECT
testing.CLIENTID,
testing.COMPANY,
testing.CONTACT,
testing.CONTACTID,
`orders`.`ORDERNO` AS `ORDERNO`,
`orders`.`BIDNO` AS `BIDNO`,
`projects`.`PROJID` AS `PROJID`,
`projects`.`PROJCODE` AS `PROJCODE`,
`projects`.`StartDate` AS `StartDate`,
`category`.`type` AS `CATEGORY`,
`projects`.`country` AS `COUNTRY`,
`projects`.`VALUE` AS `VALUE`,
`projects`.`PROCESSOR` AS `PROCESSOR`,
`projects`.`NES` AS `NES`,
`projects`.`SPECSALE` AS `SPECSALE`,
`projects`.`OFFICE` AS `OFFICE`,
`projects`.`LORM` AS `LORM`,
`lookupcountry`.`REGION` AS `REGION`
FROM
(
(
(
(
(
(
SELECT
contactmerge.CLIENTID,
contactmerge.CONTACT,
contactmerge.CONTACTID,
accountmerge.COMPANY
FROM
(
SELECT
`hdb`.`contacts`.`CONTACTID` AS `CONTACTID`,
`hdb`.`contacts`.`CLIENTID` AS `CLIENTID`,
concat(
`hdb`.`contacts`.`FIRSTNAME`,
" ",
`hdb`.`contacts`.`LASTNAME`
) AS CONTACT,
_utf8 'paradox' AS `SOURCEDATABASE`
FROM
`hdb`.`contacts`
UNION
SELECT
`sugarcrm`.`contacts`.`id` AS `CONTACTID`,
`sugarcrm`.`accounts_contacts`.`account_id` AS `CLIENTID`,
concat(
`sugarcrm`.`contacts`.`first_name`,
" ",
`sugarcrm`.`contacts`.`last_name`
) AS CONTACT,
_utf8 'sugar' AS `SOURCEDATABASE`
FROM
(
(
(
(
`sugarcrm`.`contacts`
LEFT JOIN `sugarcrm`.`email_addr_bean_rel` ON (
(
(
`sugarcrm`.`contacts`.`id` = `sugarcrm`.`email_addr_bean_rel`.`bean_id`
)
AND (
(
`sugarcrm`.`email_addr_bean_rel`.`primary_address` = 1
)
OR (
(
`sugarcrm`.`email_addr_bean_rel`.`primary_address` IS NOT NULL
)
AND (
`sugarcrm`.`email_addr_bean_rel`.`primary_address` <> 0
)
)
)
)
)
)
LEFT JOIN `sugarcrm`.`accounts_contacts` ON (
(
`sugarcrm`.`contacts`.`id` = `sugarcrm`.`accounts_contacts`.`contact_id`
)
)
)
JOIN `sugarcrm`.`email_addresses` ON (
(
`sugarcrm`.`email_addr_bean_rel`.`email_address_id` = `sugarcrm`.`email_addresses`.`id`
)
)
)
LEFT JOIN `sugarcrm`.`accounts` ON (
(
`sugarcrm`.`accounts`.`id` = `sugarcrm`.`accounts_contacts`.`account_id`
)
)
)
) AS contactmerge
LEFT JOIN (
SELECT
CLIENTID,
`hdb`.`clients`.`COMPANY` AS `COMPANY`
FROM
`hdb`.`clients`
UNION
SELECT
id AS CLIENTID,
`sugarcrm`.`accounts`.`name` AS `COMPANY`
FROM
`sugarcrm`.`accounts`
) AS accountmerge ON contactmerge.CLIENTID = accountmerge.CLIENTID
) AS testing
)
JOIN `orders` ON (
(
`testing`.`CONTACTID` = `orders`.`CONTACTID`
)
)
)
JOIN `projects` ON (
(
`orders`.`ORDERNO` = `projects`.`ORDERNO`
)
)
)
JOIN `category` ON (
(
`category`.`category_id` = `projects`.`category_id`
)
)
)
LEFT JOIN `lookupcountry` ON (
(
CONVERT (
`lookupcountry`.`COUNTRY` USING utf8
) = CONVERT (
`projects`.`country` USING utf8
)
)
)
)
ORDER BY
`testing`.`COMPANY`,
`projects`.`StartDate`
The table alias called testing is the one taking long to execute. I need to then turn this into a view
Original query without the joining of sugarcrm.
SELECT
`clients`.`CORPORATE` AS `CORPORATE`,
`clients`.`COMPANY` AS `COMPANY`,
`clients`.`CLIENTID` AS `CLIENTID`,
`contacts`.`CONTACTID` AS `CONTACTID`,
concat(
`contacts`.`LASTNAME`,
`contacts`.`FIRSTNAME`,
`contacts`.`INITIALS`
) AS `Contact`,
`orders`.`ORDERNO` AS `ORDERNO`,
`orders`.`BIDNO` AS `BIDNO`,
`projects`.`PROJID` AS `PROJID`,
`projects`.`PROJCODE` AS `PROJCODE`,
`projects`.`StartDate` AS `StartDate`,
`category`.`type` AS `CATEGORY`,
`projects`.`country` AS `COUNTRY`,
`projects`.`VALUE` AS `VALUE`,
`projects`.`PROCESSOR` AS `PROCESSOR`,
`projects`.`NES` AS `NES`,
`projects`.`SPECSALE` AS `SPECSALE`,
`projects`.`OFFICE` AS `OFFICE`,
`projects`.`LORM` AS `LORM`,
`lookupcountry`.`REGION` AS `REGION`
FROM
(
(
(
(
(
`clients`
JOIN `contacts` ON (
(
`clients`.`CLIENTID` = `contacts`.`CLIENTID`
)
)
)
JOIN `orders` ON (
(
`contacts`.`CONTACTID` = `orders`.`CONTACTID`
)
)
)
JOIN `projects` ON (
(
`orders`.`ORDERNO` = `projects`.`ORDERNO`
)
)
)
JOIN `category` ON (
(
`category`.`category_id` = `projects`.`category_id`
)
)
)
LEFT JOIN `lookupcountry` ON (
(
CONVERT (
`lookupcountry`.`COUNTRY` USING utf8
) = CONVERT (
`projects`.`country` USING utf8
)
)
)
)
ORDER BY
`clients`.`CORPORATE`,
`clients`.`COMPANY`,
`contacts`.`LASTNAME`,
`projects`.`StartDate`
Your LEFT JOIN from sugarcrm.contacts to sugarcrm.email_addr_bean_rel
ON the id=bean_id is ok, but then your test for Primary_Address = 1
OR ( primary address IS NOT NULL AND primary_address <> 0 ) is wasteful.
Not null mean it has a value. The first qualifier of 1 is ok, but then
you test for any address not equal to 0 (thus 1 is, but so is 2, 3, 400, 1809 or
any other number. So why not just take how I've simplified it.
SELECT
O.ORDERNO,
O.BIDNO,
CASE when c.ContactID IS NULL
then sc.id
ELSE c.contactid END as ContactID,
CASE when c.ContactID IS NULL
then sac.account_id
ELSE c.clientid END as ClientID,
CASE when c.ContactID IS NULL
then concat( sc.first_name, " ", sc.last_name )
ELSE concat( c.FIRSTNAME, " ", c.LASTNAME ) END as Contact,
CASE when c.ContactID IS NULL
then sCli.`name`
ELSE cCli.Company END as Company,
CASE when c.ContactID IS NULL
then _utf8 'sugar'
ELSE _utf8 'paradox' END as SOURCEDATABASE,
P.PROJID,
P.PROJCODE,
P.StartDate,
Cat.`type` AS CATEGORY,
P.`country` AS COUNTRY,
P.`VALUE` AS `VALUE`,
P.PROCESSOR,
P.NES,
P.SPECSALE,
P.OFFICE,
P.LORM,
LC.REGION
FROM
orders O
JOIN projects P
ON O.ORDERNO = P.ORDERNO
JOIN category Cat
ON P.category_id = Cat.category_id
LEFT JOIN lookupcountry LC
ON CONVERT( P.`country` USING utf8 ) = CONVERT( LC.COUNTRY USING utf8 )
LEFT JOIN hdb.contacts c
ON O.ContactID = c.ClientID
LEFT JOIN hdb.clients cCli
ON c.ClientID = cCli.ClientID
LEFT JOIN sugarcrm.contacts sc
ON O.ContactID = sc.id
LEFT JOIN sugarcrm.accounts sCli
ON sc.id = sCli.id
LEFT JOIN sugarcrm.accounts_contacts sac
ON sc.id = sac.contact_id
LEFT JOIN sugarcrm.accounts Acc
ON sac.account_id = Acc.id
LEFT JOIN sugarcrm.email_addr_bean_rel EABR
ON sc.id = EABR.bean_id
AND EABR.primary_address IS NOT NULL
LEFT JOIN sugarcrm.email_addresses EA
ON EABR.email_address_id = EA.id
ORDER BY
CASE when c.ContactID IS NULL
then sCli.`name`
ELSE cCli.Company END,
P.StartDate
I don't mind helping, but from now on, you should take a look at what I'm doing... Establish the relationships... Start with the basis of your data (orders) and look at ONE PATH on how to connect to your "contacts" table... Write those joins (as left-joins). THEN, write your paths to the SUGAR account contacts and write THOSE joins (also left-joins). Don't try to prequery all possible contacts, but using the CASE/WHEN to determine which to get based on a null route vs not just as I have with the contact, client, company, etc. You will get the data from one path vs the other... just keep it consistent.