将第三个表中的SQL查询合并到从2个不同表中计数的现有查询

时间:2013-11-26 01:38:07

标签: mysql sql

我有一个查询计算来自2013年11月11日至11月24日期间来自两个不同表的来电和来电。

SELECT d.id_client,
   d.login,
   Coalesce(c.total, 0)  AS calls,
   Coalesce(fc.total, 0) AS calls_failed
FROM   api.clients d
   LEFT OUTER JOIN (SELECT Count(*) AS total,
                           id_client
                    FROM   voip.calls c
                    WHERE  c.call_start >= '2013-11-11 00:00:00'
                           AND c.call_start < '2013-11-25 00:00:00'
                    GROUP  BY id_client) c
                ON d.id_client = c.id_client
   LEFT OUTER JOIN (SELECT Count(*) AS total,
                           id_client
                    FROM   voip.callsfailed c
                    WHERE  c.call_start >= '2013-11-11 00:00:00'
                           AND c.call_start < '2013-11-25 00:00:00'
                           AND c.ie_error_number <> 0
                    GROUP  BY id_client) fc
                ON d.id_client = fc.id_client
    WHERE  d.id_client IN (SELECT e.idclient
                   FROM   voip.invoiceclients e
                   WHERE  e.clientnr = 'demo')  

我有一个单独的查询,为每个客户端提供client_balance,mobile_number,名称。

SELECT cr.id_client,
   inv.taxid AS company,
   inv.name,
   inv.lastname,
   inv.mobilephone,
   cr.account_state
FROM   clientsretail cr,
   invoiceclients inv
WHERE  cr.id_client = inv.idclient
   AND inv.clientnr = 'demo'
ORDER  BY inv.taxid,
      inv.name; 

如何合并这些查询以生成以下输出: id_client,公司名称,姓氏,Mobilephone,登录,电话,失败,调用,平衡

我尝试使用以下查询执行一些小步骤,但失败了:

SELECT d.id_client, d.login,
COALESCE(c.total, 0) AS calls, COALESCE(fc.total, 0) AS calls_failed
FROM api.clients d
LEFT OUTER JOIN
(
    SELECT COUNT(*) AS total, id_client
    FROM voip.calls c
    WHERE c.call_start >= '2013-11-11 00:00:00'
      AND c.call_start < '2013-11-25 00:00:00'
    GROUP BY id_client
) c ON d.id_client = c.id_client
LEFT OUTER JOIN
(
    SELECT COUNT(*) AS total, id_client
    FROM voip.callsfailed c
    WHERE c.call_start >= '2013-11-11 00:00:00'
      AND c.call_start < '2013-11-25 00:00:00'
      AND c.IE_error_number <> 0
    GROUP BY id_client
) fc ON d.id_client = fc.id_client
LEFT OUTER JOIN
(
    SELECT c.idclient,
      c.taxid,
      c.name,
      c.lastname,
      c.mobilephone
    FROM voip.invoiceclients c
) v ON d.id_client=v.idclient
WHERE d.id_client IN
(
SELECT e.idclient
FROM voip.invoiceclients e
WHERE e.clientnr='demo'
)

您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在

附近使用正确的语法
 'FROM voip.invoiceclients c
) v ON d.id_client=v.idclient WHERE d.id_clie' at line 28

1 个答案:

答案 0 :(得分:1)

您的代码绝对正确,只有一个小的语法错误。只需在select语句中删除c.mobilephone之后的逗号(','),您的语法错误问题就会解决,查询将会运行。