用于计算相应条目的SQL语句

时间:2015-04-27 12:34:10

标签: sql

我在计算数据库中客户端的相应联系人,网站和设备时遇到问题。

我的表是:

TABLE Devis 
idDevis (PK)
idSiteClient (FK)

TABLE SiteClient
idSiteClient (PK)
idClient (FK)

 TABLE Client
    idClient (PK)

 TABLE Contact
    idContact (PK)
    idClient (FK)

我目前的陈述是

$requete = myPDO::getInstance()->prepare(<<<SQL
        SELECT COUNT(sc.idSiteClient), COUNT(dvs.idDevis), COUNT(ct.idContact)
        FROM SiteClient sc, Devis dvs, Client clt, Contact ct
        WHERE dvs.idSiteClient = sc.idSiteClient
        AND sc.idClient = clt.idClient
        AND clt.idClient = ct.idClient
        AND clt.idClient = :id
SQL
);

    $requete->execute(array(":id" => $id));

但它给了我15,15,15这是错的,我应该有5个站点,2个Devis和5个联系

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

使用它:

WITH 
  clt1 AS (SELECT * FROM Client clt WHERE clt.idClient = :id),
  ct1 AS (SELECT COUNT(*) cnt, ct.* FROM Contact ct JOIN clt1 ON clt1.idClient = ct.idClient),
  sc1 AS (SELECT COUNT(*) cnt, sc.* FROM SiteClient sc JOIN clt1 ON clt1.idClient = sc.idClient),
  dvs1 AS (SELECT COUNT(*) cnt, dvs.* FROM Devis dvs JOIN sc1 ON sc1.idSiteClient = dvs.idSiteClient)
SELECT DISTINCT NVL(sc1.cnt, 0), NVL(dvs1.cnt, 0), NVL(ct1.cnt, 0)
FROM sc1, dvs1, ct1

答案 1 :(得分:0)

尝试使用Distinct

   SELECT COUNT(distinct sc.idSiteClient), 
       COUNT(distinct  dvs.idDevis), COUNT(distinct ct.idContact)
    FROM SiteClient sc, Devis dvs, Client clt, Contact ct
    WHERE dvs.idSiteClient = sc.idSiteClient
    AND sc.idClient = clt.idClient
    AND clt.idClient = ct.idClient
    AND clt.idClient = :id

答案 2 :(得分:0)

你可以尝试这个

SELECT 
cl.idClient, 
sc.SiteNo, 
con.ContactNo,
dev.DevisNo

FROM Client cl
    LEFT JOIN ( SELECT COUNT(distinct idClient) AS SiteNo, idClient, idSiteClient FROM SiteClient GROUP BY idClient, idSiteClient) sc ON  cl.idClient = st.idClient
    LEFT JOIN ( SELECT COUNT(*) AS ContactNo, idClient FROM Contact GROUP BY idClient) con ON  cl.idClient = con.idClient
    LEFT JOIN ( SELECT COUNT(*) AS DevisNo, idSiteClient FROM Devis GROUP BY idSiteClient) dev ON  sc.idSiteClient = dev.idSiteClient
WHERE 
cl.idClient = :id