I have a composite query where I perform UNION between multiple table. Now My query fails when table does not exists. (Use case is that a table on which select query is perform is created on 5th of every month so my query fails till 5th of the month)
So I want my query to return data even if UNION OR JOIN fails due to Table does not exists error.
Now I tried using IF EXISTS
but I am not sure how I should be using it and it resulted in syntax error.
Query Faills where table name is : THE TABLE WHICH DOES NOT EXISTS
This is my query :
SELECT CONCAT(CONVERT_TZ(calldate,'-4:00','+5:30'),' IST') AS calldate,
src AS clid,
`column1`,
`columnn`,
`columnn`,
`columnn`,
`columnn`
FROM `Table1`
WHERE `accocode`='123456'
AND calleedate > DATE_SUB(NOW(), INTERVAL 7 DAY)
AND callee LIKE 'Incoming%'
UNION
SELECT CONCAT(CONVERT_TZ(calldate,'-4:00','+5:30'),' IST') AS calleedate,
(CASE
WHEN (position('SIP/' IN channel)>0) THEN substring(channel,position('/' IN channel)+1,position('_' IN channel)-position('/' IN channel)-1)
ELSE substring(channel,position('/' IN channel)+1,position('@' IN channel)-position('/' IN channel)-1)
END) AS clid,
(CASE
WHEN (`callee` = 'Outgoing') THEN CONCAT(`dst`,' - ',`country`)
ELSE `dst`
END)AS dst1,
`columnn`,
`columnn`,
`columnn`,
`columnn`
FROM `Table1`
JOIN
(SELECT *
FROM mvc_v2.isd_code
ORDER BY `code` DESC)isd ON locate(isd.code,`dst`)=1
WHERE `accountcode`='1184372641'
AND calldate > DATE_SUB(NOW(), INTERVAL 7 DAY)
AND NOT (calltype LIKE 'Incoming%')
UNION
SELECT CONCAT(CONVERT_TZ(calldate,'-4:00','+5:30'),' IST') AS calldate,
src AS clid,
`columnn`,
`columnn`,
`columnn`,
`columnn`,
`columnn`
FROM `THE TABLE WHICH DOES NOT EXISTS`
WHERE `accountcode`='1184372641'
AND calldate > DATE_SUB(NOW(), INTERVAL 7 DAY)
AND calltype LIKE 'Incoming%'
UNION
SELECT CONCAT(CONVERT_TZ(calldate,'-4:00','+5:30'),' IST') AS calldate,
(CASE
WHEN (position('SIP/' IN channel)>0) THEN substring(channel,position('/' IN channel)+1,position('_' IN channel)-position('/' IN channel)-1)
ELSE substring(channel,position('/' IN channel)+1,position('@' IN channel)-position('/' IN channel)-1)
END) AS clid,
(CASE
WHEN (`calleeetype` = 'Outgoing') THEN CONCAT(`dst`,' - ',`country`)
ELSE `dst`
END)AS dst1,
`columnn`,
`columnn`,
`columnn`,
`columnn`
FROM `THE TABLE WHICH DOES NOT EXISTS`
JOIN
(SELECT *
FROM mvc_v2.isd_code
ORDER BY `code` DESC)isd ON locate(isd.code,`dst`)=1
WHERE `accocode`='123456'
AND calldate > DATE_SUB(NOW(), INTERVAL 7 DAY)
AND NOT (calleetype LIKE 'Incoming%')
ORDER BY `calleeedate` DESC