复杂的MySQL查询问题

时间:2011-03-23 12:38:25

标签: mysql select

我的MySQL查询有问题: 我有两张桌子: - clustercategories - 域名

现在我有一个SQL查询,它列出了具有类别名称的特定类别的所有域 - 这是我的查询:

SELECT domains.*, clustercategories.clustercategoryname
FROM (domains, clustercategories)
WHERE ((clustercategories.id = 3 AND (domains.cluster1id = 3 OR domains.cluster2id = 3)) 
OR (clustercategories.id = 10 AND (domains.cluster1id = 10 OR domains.cluster2id = 10))) 
AND domains.status = '1' 
GROUP BY domains.name 
ORDER BY domains.name

现在的问题是,我还有第三个表“子页面”,我想要计算状态='1'的特定域的所有条目,我不知道如何修改我的查询工作 - 我尝试了这个查询,但我没有得到任何结果:

SELECT domains.*, clustercategories.clustercategoryname
FROM (domains, clustercategories)
WHERE ((clustercategories.id = 3 AND (domains.cluster1id = 3 OR domains.cluster2id = 3) AND (SELECT COUNT(*) AS total FROM subpages WHERE subpages.domainid = domains.id AND subpages.status = '1')) 
OR (clustercategories.id = 10 AND (domains.cluster1id = 10 OR domains.cluster2id = 10) AND (SELECT COUNT(*) AS total FROM subpages WHERE subpages.domainid = domains.id AND subpages.status = '1'))) 
AND domains.status = '1' 
GROUP BY domains.name 
ORDER BY domains.name

有没有人有任何想法?

2 个答案:

答案 0 :(得分:2)

我认为您希望将子查询放入投影中,如下所示:

SELECT domains.*, clustercategories.clustercategoryname, 
(SELECT COUNT(*) FROM subpages WHERE subpages.domainid = domains.id AND subpages.status = '1') AS total
FROM domains, clustercategories
WHERE ((clustercategories.id = 3 AND (domains.cluster1id = 3 OR domains.cluster2id = 3)) 
OR (clustercategories.id = 10 AND (domains.cluster1id = 10 OR domains.cluster2id = 10))) 
AND domains.status = '1' 
GROUP BY domains.name 
ORDER BY domains.name

答案 1 :(得分:1)

在我看来,您的第一个查询可以像这样重写

SELECT  d.*
        , cc.clustercategoryname
FROM    domains d
        INNER JOIN clustercategories cc
          ON cc.id = d.cluster1id 
          OR cc.id = d.cluster2id
WHERE   cc.id IN (3, 10)
        AND d.status = '1'                                           
GROUP BY 
        d.name
ORDER BY 
        d.name

因此可以像这样添加子页数

  SELECT  d.*
          , cc.clustercategoryname
          , sp.total
  FROM    domains d
          INNER JOIN clustercategories cc 
            ON cc.id = d.cluster1id 
               OR cc.id = d.cluster2id
          LEFT OUTER JOIN (
            SELECT  COUNT(*) AS total
                    , domainid
            FROM    subpages
            WHERE   subpages.status = '1'
            GROUP BY
                    domainid
          ) sp ON sp.domainid = d.domainid          
  WHERE   cc.id IN (3, 10)
          AND d.status = '1'                                           
  GROUP BY 
          d.name
  ORDER BY 
          d.name