仅当数据库

时间:2017-08-02 08:25:41

标签: mysql union union-all

我有一个复合查询,我在多个表之间执行UNION。现在,当表不存在时,我的查询失败。 (用例是每月5日创建一个执行选择查询的表,因此我的查询将在每月5日之前失败)

所以我希望我的查询返回数据,即使UNION OR JOIN因Table不存在而失败也会出错。

现在我尝试使用IF EXISTS,但我不确定应该如何使用它,这会导致语法错误。

查询表格名称所在的地址:不存在的表格

这是我的疑问:

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

1 个答案:

答案 0 :(得分:1)

您可以使用information_schema检查表格是否存在

set @tablecount= 0;
select  count(TABLE_NAME) into @tablecount from information_schema.`COLUMNS` where TABLE_NAME = 'tableNameHere';
select @tablecount

您可以在此处使用计数:

if(@tablecount>0)
Your code here.......