首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多表mysql查询

多表mysql查询
EN

Stack Overflow用户
提问于 2010-12-13 16:47:59
回答 3查看 115关注 0票数 0

我有4张桌子

代码语言:javascript
复制
Table: Category
    CategoryID (int)
    Name (varchar)
Table: Products
    ProductID (int)
    CategoryID (int)
    Name (varchar)
    Description (text)
Table: Sales
    SalesID (int)
    ProductID (int)
Table: Links
    LinkID (int)
    ProductID (int)

现在我需要将数据显示为:

代码语言:javascript
复制
CategoryName     Total Products     Total Sales     Total Links
    ABC                5                 12            50
    XYZ               12                 26            10

我如何才能做到这一点,可能是在单个查询中

感谢您的帮助

谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-12-13 16:56:02

代码语言:javascript
复制
  SELECT CategoryName, Count(distinct p.ProductId) TotalProducts, Count(distinct s.SalesId) TotalSales, 
        COUNT(distinct l.LinkId) TotalLinks
  FROM Products p JOIN SALES s on p.ProductId = s.ProductId
       JOIN Categories c ON c.CategoryId = p.CategoryId
       JOIN Links l ON p.ProductId = l.LinkId
  GROUP BY CategoryName
票数 0
EN

Stack Overflow用户

发布于 2010-12-13 16:53:39

代码语言:javascript
复制
SELECT
       CAT.Name CategoryName,
       (SELECT COUNT(P.ProductsID) FROM Products P WHERE P.CategoryID=CAT.CategoryID) TotalProducts,
       (SELECT COUNT(S.SalesID) FROM Sales S JOIN Products P ON S.ProductID=P.ProductID WHERE P.CategoryID=CAT.CategoryID) TotalSales,
       (SELECT COUNT(L.LinkID) FROM Links L JOIN Products P ON L.ProductID=P.ProductID WHERE P.CategoryID=CAT.CategoryID) TotalLinks
FROM 
       CATEGORY CAT
票数 0
EN

Stack Overflow用户

发布于 2010-12-13 16:55:31

代码语言:javascript
复制
select
    c.CategoryId,
    c.name as CategoryName,
    count(p.ProductId) as TotalProducts,
    (select count(s.salesid) from sales s where s.ProductId = p.ProductId) as TotalSales,
    (select count(l.linkid) from products l where l.ProductId = p.ProductId) as TotalLinks
from
  Category c
  left join Products p on p.CategoryId = c.CategoryId
group by
  c.CategoryId,
  c.Name
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4427099

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档