I have a table 'booking_summary' which stores the type of method (method = Air or Sea).
I have to join this table with one of the two other tables depending on the method column.
If the method is Air,then the table to join is booking_air,if sea then it is booking_sea.
I do not want to run multiple queries on this particular page.
This is my latest attempt,that has obviously failed.The table_name with alias is the table i want in the same query.
$sql = "select case when a.shipping_method = 'Sea' then 'booking_sea' else 'booking_air' end 'table_name',
case when a.user_id ='$active_id' then 'y' else 'no' end 'generate_access',
case when c.mbl is NULL then 'Pending' else c.mbl end 'mbl_status',
case when c.hbl is NULL then 'Pending' else c.hbl end 'hbl_status',
a.*,b.user_name
from booking_summary a
left join registered_users b
on a.user_id = b.user_id
left join table_name c
on a.id = c.id
where (a.user_id = '$active_id' or a.forwarder='$active_id')";
Any advice would be very helpful. Thanks
Om I'm not sure if this is going to work but, anyhow...
$sql = "select case
when a.user_id ='$active_id' then 'y'
else 'no' end 'generate_access',
if(a.shipping_method = 'Sea',
case when c.mbl is NULL then 'Pending' else c.mbl end,
case when d.mbl is NULL then 'Pending' else d.mbl end ) 'mbl_status',
if(a.shipping_method = 'Sea',
case when c.hbl is NULL then 'Pending' else c.hbl end,
case when d.hbl is NULL then 'Pending' else d.hbl end ) 'hbl_status',
a.*,b.user_name
from booking_summary a
left join registered_users b on a.user_id = b.user_id
left join booking_sea c on a.id = c.id
left join bookin_air d on a.id=d.id
where (a.user_id = '$active_id' or a.forwarder='$active_id')";
Without fully understanding your structure, I can think of this solution
SELECT a.shipping_method
FROM shipping_summary AS A
LEFT JOIN (SELECT *,
'AIR' AS METHOD
FROM shipping_air) AS B
ON A.shipping_method = B.method
LEFT JOIN (SELECT *,
'SEA' AS METHOD
FROM shipping_sea) AS C
ON A.shipping_method = C.method
This is a high level answer as I do not have the fields to be selected and more ways to optimise the query.
Related
I am using below query to fetch the report for 10 different ids using union-all.Is there any way to reduce the query ?
SELECT
sc.consentid,
CASE
WHEN ue.userid IS NULL THEN 'No'
ELSE 'Yes'
END ,
sc.firstname,
sc.lastname,
CASE
WHEN SUM(time_on_page) > 0 THEN ROUND(SUM(time_on_page) / 60, 2)
ELSE 'No videos watched'
END AS timeonpage,
'ID1' ,
CASE
WHEN COUNT(DISTINCT COALESCE(article, video)) > 0 THEN COUNT(DISTINCT COALESCE(article, video))
ELSE 'no video in list watched'
END AS countvideoswatched
FROM
studentconsent AS sc
LEFT JOIN
useremails AS ue USING (email)
LEFT JOIN
masterstats_innodb AS m ON ue.userid = m.user_id
WHERE
(sc.email LIKE '%.it'
AND (sc.consentid IS NOT NULL
AND m.id IS NULL)
OR (m.id IS NOT NULL
AND m.timestamp >= '2020-12-01'
AND (video IN (SELECT
objectid
FROM
playlists
JOIN
playlisttoobjects USING (playlistid)
WHERE
unique_id = 'ID1'
AND objecttype = 'article'))))
GROUP BY sc.consentid
union all (query2 with differentid)....so on
Here I need to use union-all command to combine all 10 select queries with different id.Any way to reduce it?
query taking 1 minute to fetch results
SELECT
`jp`.`id`,
`jp`.`title` AS game_title,
`jp`.`game_type`,
`jp`.`state_abb` AS game_state,
`jp`.`location` AS game_city,
`jp`.`zipcode` AS game_zipcode,
`jp`.`modified_on`,
`jp`.`posted_on`,
`jp`.`game_referal_amount`,
`jp`.`games_referal_amount_type`,
`jp`.`status`,
`jp`.`is_flaged`,
`u`.`id` AS employer_id,
`u`.`email` AS employer_email,
`u`.`name` AS employer_name,
`jf`.`name` AS game_function,
`jp`.`game_freeze_status`,
`jp`.`game_statistics`,
`jp`.`ats_value`,
`jp`.`integration_id`,
`u`.`account_manager_id`,
`jp`.`model_game`,
`jp`.`group_id`,
(CASE
WHEN jp.group_id != '0' THEN gm.group_name
ELSE 'NA'
END) AS group_name,
`jp`.`priority_game`,
(CASE
WHEN jp.country != 'US' THEN jp.country_name
ELSE ''
END) AS game_country,
IFNULL((CASE
WHEN
`jp`.`account_manager_id` IS NULL
OR `jp`.`account_manager_id` = 0
THEN
(SELECT
(CASE
WHEN
account_manager_id IS NULL
OR account_manager_id = 0
THEN
`u`.`account_manager_id`
ELSE account_manager_id
END) AS account_manager_id
FROM
user_user
WHERE
id = (SELECT
user_id
FROM
game_user_assigned
WHERE
game_id = `jp`.`id`
LIMIT 1))
ELSE `jp`.`account_manager_id`
END),
`u`.`account_manager_id`) AS acc,
(SELECT
COUNT(recach_limit_id)
FROM
recach_limit
WHERE
recach_limit = '1'
AND recach_limit_game_id = rpr.recach_limit_game_id) AS somewhatgame,
(SELECT
COUNT(recach_limit_id)
FROM
recach_limit
WHERE
recach_limit = '2'
AND recach_limit_game_id = rpr.recach_limit_game_id) AS verygamecommitted,
(SELECT
COUNT(recach_limit_id)
FROM
recach_limit
WHERE
recach_limit = '3'
AND recach_limit_game_id = rpr.recach_limit_game_id) AS notgame,
(SELECT
COUNT(joa.id) AS applicationcount
FROM
game_refer_to_member jrmm
INNER JOIN
game_refer jrr ON jrr.id = jrmm.rid
INNER JOIN
game_applied joa ON jrmm.id = joa.referred_by
WHERE
jrmm.STATUS = '1'
AND jrr.referby_user_id IN (SELECT
ab_testing_user_id
FROM
ab_testing)
AND joa.game_post_id = rpr.recach_limit_game_id
AND (rpr.recach_limit = 1
OR rpr.recach_limit = 2)) AS gamecount
FROM
(`game_post` AS jp)
JOIN
`user_info` AS u ON `jp`.`user_user_id` = `u`.`id`
JOIN
`game_functional` jf ON `jp`.`game_functional_id` = `jf`.`id`
LEFT JOIN
`group_musesm` gm ON `gm`.`group_id` = `jp`.`group_id`
LEFT JOIN
`recach_limit` rpr ON `jp`.`id` = `rpr`.`recach_limit_game_id`
WHERE
`jp`.`status` != '3'
GROUP BY `jp`.`id`
ORDER BY `posted_on` DESC
LIMIT 10
I would first suggest not nesting select statements because this will cause an n^x performance hit on every xth level and I see at least 3 levels of selects inside this query.
Add index
INDEX(status, posted_on)
Move LIMIT inside
Then, instead of saying
FROM (`game_post` AS jp)
say
FROM ( SELECT id FROM game_post
WHERE status != 3
ORDER BY posted_on DESC
LIMIT 10 ) AS ids
JOIN game_post AS jp USING(id)
(I am assuming that the PK of jp is (id)?)
That should efficiently use the new index to get the 10 ids needed. Then it will reach back into game_post to get the other columns.
LEFT
Also, don't say LEFT unless you need it. It costs something to generate NULLs that you may not be needing.
Is GROUP BY necessary?
If you remove the GROUP BY, does it show dup ids? The above changes may have eliminated the need.
IN(SELECT) may optimize poorly
Change
AND jrr.referby_user_id IN ( SELECT ab_testing_user_id
FROM ab_testing )
to
AND EXISTS ( SELECT * FROM ab_testing
WHERE ab_testing_user_id = jrr.referby_user_id )
(This change may or may not help, depending on the version you are running.)
More
Please provide EXPLAIN SELECT if you need further assistance.
I have a problem how to combine the sql statements (inner join and union all. as a Newbie in SQL. Hopefully all members can help me to solve the problems.attached herewith the SQL. The leave_Trx and leave_History contain same values that need to be union. Thank you.
select m.name, t.startdt, t.enddt,t.noday,t.createdDT,
(case when t.approveST = 'Y' then 'Approved' when t.approveST = 'N' then 'Not Approved' else 'Pending' end) as appST
from leave_Trx t
inner join leave_MType m on m.typeID = t.trxID
inner join hr_personaldata b on b.pers_ID = #pers_ID
where year(t.startdt) = #yyear
and b.pers_ID = #pers_ID and b.pers_name LIKE '%'+#pers_name+'%'
and b.pers_compID LIKE ''+#compID+''
union all
select * from leave_History h
where year(h.startdt) = #yyear and h.status = 'A'
ORDER BY t.startdt
select t.pers_ID,t.startdt, t.enddt,t.noday,t.createdDT,
(case when t.approveST = 'Y' then 'Approved' when t.approveST = 'N' then 'Not Approved' else 'Pending' end) as appST
from leave_Trx t
inner join leave_MType m on m.typeID = t.pers_ID
inner join hr_personaldata l on l.pers_ID = #pers_ID
where year(t.startdt) = #yyear and t.status = 'A'
union all
select h.pers_ID, h.startdt, h.enddt,h.noday,h.createdDT,
(case when h.approveST = 'Y' then 'Approved' when h.approveST = 'N' then 'Not Approved' else 'Pending' end) as appST
from leave_History h
inner join leave_MType m on m.typeID = h.pers_ID
inner join hr_personaldata b on b.pers_ID = #pers_ID
where year(h.startdt) = #yyear and h.status = 'A'
I have a query with a CASE statement that determines the variable object_name this variable is derived from either the x_ambitions table or the x_trybes table. The queries below were combined so that I could keep it simple by just executing one SQL query.
I've split the SELECT statement into two so that you have a better understanding. The two queries below. Work and pull the correct object_name from the database.
The problem I'm having when I combine the two queries is that the cases 'new_join_ambition','new_created_ambition','new_liked_ambition' object_name returns NULL in the LEFT JOIN.
In the combined query, If I bring the cases: 'new_join_ambition','new_created_ambition','new_liked_ambition' above the 'new_join_trybe','new_created_trybe','new_liked_trybe' cases. The opposite happens. The trybe rows return NULL.
The two SQL queries:
A: (Retrieve Object A)
SELECT
s.id,
s.object_id,
s.type,
s.postee_id,
s.user_id,
s.text,
s.registered,
CONCAT(u.x_first_name,' ',u.x_last_name) AS postee_name,
ui.image_id AS postee_image_id,
CASE s.type
WHEN 'new_join_ambition'
OR 'new_created_ambition'
OR 'new_liked_ambition'
THEN a.name
ELSE 'a'
END AS object_name
FROM
x_share s
LEFT JOIN
x_user u ON u.id = s.postee_id
LEFT JOIN
x_user_images ui ON ui.user_id = s.postee_id
LEFT JOIN
x_ambitions a ON s.type IN ('new_join_ambition', 'new_created_ambition', 'new_liked_ambition') AND s.object_id = a.id
LEFT JOIN
x_ambition_invites ai ON s.type IN ('new_join_ambition') AND s.object_id = ai.ambition_id AND s.postee_id = ai.to
LEFT JOIN
x_ambition_likes al ON s.type IN ('new_liked_ambition') AND s.object_id = al.ambition_id AND s.postee_id = al.profile_id
LEFT JOIN
x_ambition_owner aoo ON s.type IN ('new_created_ambition') AND s.object_id = aoo.ambition_id
WHERE
s.user_id = '%s'
ORDER BY
s.registered DESC
B: (Retrieve Object B)
SELECT
s.id,
s.object_id,
s.type,
s.postee_id,
s.user_id,
s.text,
s.registered,
CONCAT(u.x_first_name,' ',u.x_last_name) AS postee_name,
ui.image_id AS postee_image_id,
CASE s.type
WHEN 'new_join_trybe'
OR 'new_created_trybe'
OR 'new_liked_trybe'
THEN t.name
ELSE 'a'
END AS object_name
FROM
x_share s
LEFT JOIN
x_user u ON u.id = s.postee_id
LEFT JOIN
x_user_images ui ON ui.user_id = s.postee_id
LEFT JOIN
x_trybes t ON s.type IN ('new_join_trybe', 'new_created_trybe', 'new_liked_trybe') AND s.object_id = t.id
LEFT JOIN
x_trybe_invites ti ON s.type IN ('new_join_trybe') AND s.object_id = ti.trybe_id AND s.postee_id = ti.to
LEFT JOIN
x_trybes_likes tl ON s.type IN ('new_liked_trybe') AND s.object_id = tl.trybe_id AND s.postee_id = tl.profile_id
LEFT JOIN
x_trybe_owner too ON s.type IN ('new_created_trybe') AND s.object_id = too.trybe_id
WHERE
s.user_id = '%s'
ORDER BY
s.registered DESC
I've ran both the queries and have captured images of the results of both queries.
Set A:
Set B:
How can I combine the two without the object_name returning NULL? If you have any questions please use the comments and I'll reply without hesitation.
Thanks in advance
I don't know about the rest of your query, but your case statement is incorrect. You have:
(CASE s.type
WHEN 'new_join_ambition' OR 'new_created_ambition' OR 'new_liked_ambition'
THEN a.name
ELSE 'a'
END) AS object_name
The ORs end up treating the values as numbers, so this is equivalent to WHEN 0 THEN . . ..
What you want is this form of the case:
(CASE WHEN s.type IN ('new_join_ambition', 'new_created_ambition', 'new_liked_ambition')
THEN a.name
ELSE 'a'
END) AS object_name
Having an issue with a specific section of a query using DATEDIFF:
select 1 as NumApps,
LenderInfo.Name as LenderName,
CASE WHEN ApplicationInfo.AEType IS NULL OR ApplicationInfo.AEType = 0 THEN 'Unknown' ELSECONCAT (AEContact.FirstName, ' ', AEContact.LastName) END As AEName,
CASE WHEN b.createdby > 0 THEN CONCAT (contactinfo.firstname, ' ', contactinfo.lastname) END AS LogActionBy,
CASE WHEN ApplicationInfo.RecertificationById IS NULL THEN CASE WHEN ApplicationInfo.IsCorrespondent IS NULL OR ApplicationInfo.IsCorrespondent = 0 THEN 'Wholesale' ELSE 'Correspondent' END ELSE CASE WHEN ApplicationInfo.IsCorrespondent IS NULL OR ApplicationInfo.IsCorrespondent = 0 THEN 'Wholesale - Recert' ELSE 'Correspondent- Recert' END END As AppType,
Applicationinfo.SubmissionDate,
ApplicationInfo.ApplicationID,
b.status AS LogStatus,
b.CreatedOn as LogDate,
companyinfo.Name,
companyinfo.NMLSEntityID,
applicationinfo.CreatedDate,
ApplicationInfo.Status as ApplicationStatus,
ApplicationInfo.StatusChangeDate,
DATEDIFF ((Select CreatedOn From ApplicationStatusChangeLog a where a.ApplicationId = b.ApplicationId
And a.status = 'Approved'),(Select CreatedOn From ApplicationStatusChangeLog a Where a.ApplicationId = b.ApplicationId And a.status = 'Pending Approval')) AS DaysToApprove
from applicationinfo
INNER JOIN CompanyInfo ON(ApplicationInfo.CompanyId = CompanyInfo.CompanyId)
left join CompanyInfo As LenderInfo ON (ApplicationInfo.LenderId = LenderInfo.CompanyId)
LEFT JOIN UserInfo ON (UserInfo.UserId = ApplicationInfo.LastModifiedById)
LEFT JOIN ContactInfo ON UserInfo.ContactId = ContactInfo.ContactId
LEFT JOIN ContactInfo AS Comergence ON(ApplicationInfo.ComergenceRepId = Comergence.ContactId)
LEFT JOIN UserInfo AS AEUser ON(AEUser.UserId = ApplicationInfo.AEType)
left join paymentinfo on applicationinfo.applicationid = paymentinfo.applicationid
Inner join applicationstatuschangelog b on applicationinfo.applicationid = b.applicationid
LEFT JOIN ContactInfo AS AEContact ON(AEContact.ContactId = AEUser.ContactId)
LEFT JOIN UserInfo AS StatusUser ON(StatusUser.UserId = ApplicationInfo.StatusChangeById)
LEFT JOIN ContactInfo AS StatusContact ON(StatusContact.ContactId = StatusUser.ContactId)
LEFT JOIN ApprovalStatus ON(ApplicationInfo.ApplicationId = ApprovalStatus.ApplicationId AND ApplicationInfo.CompanyId = ApprovalStatus.CompanyHQId
AND ApplicationInfo.CompanyId = ApprovalStatus.CompanyId)
Where ApplicationInfo.Status NOT In ('Approved Monitor Only')
AND LenderInfo.ActiveLenderContract = 1
AND COALESCE(ApplicationInfo.IsDeleted,0) <> 1
AND b.Status NOT IN ('Incomplete', 'Not Submitted')
Group BY b.ApplicationID`
I've seen some people mentioning using IN instead of = within the subquery, but I can't seem to get it to work. Any ideas out there? Thanks in advance.
I was able to get the query working by adding 'Limit 1' after the identified status:
(Select CreatedOn From ApplicationStatusChangeLog a where a.ApplicationId = b.ApplicationId
And a.status = 'Approved' LIMIT 1),(Select CreatedOn From ApplicationStatusChangeLog a Where a.ApplicationId = b.ApplicationId And a.status = 'Pending Approval' LIMIT 1)