MySQL Query从多个表中获取数据

时间:2010-11-24 13:02:39

标签: mysql

我有以下表格 1)产品(产品,名称,描述,价格)
2)销售(salesid,productid,buyername,buyeremail,status)
3)ProductViews(viewid,productid)

现在,我需要一个可以输出为
的查询 产品编号产品价格TOTALVIEWS TotalSales

帮助表示感谢,谢谢。

4 个答案:

答案 0 :(得分:1)

您可以使用子查询来获取观看次数和销售额:

SELECT 
    a.productid,
    a.name,
    a.price,
    (SELECT COUNT(b.viewid)
     FROM ProductViews b
     WHERE b.productid = a.productid) as TotalViews,
    (SELECT COUNT(c.salesid)
     FROM Sales c
     WHERE c.productid = a.productid) as TotalSales
FROM
    Products a

答案 1 :(得分:1)

SELECT p.productid, p.name, p.price, COUNT(pv.viewid) AS totalviews, COUNT(s.salesid) AS totalsales 
FROM Products p
LEFT JOIN Sales s ON s.productid = p.productid
LEFT JOIN ProductViews pv ON pv.productid = p.productid
GROUP BY p.productid, p.name, p.price

为了完整起见而扩展组,但它可能只是p.productid。

答案 2 :(得分:0)

Select p.ProductID, p.ProductName, p.Price, s.c as TotalSales, v.c as TotalViews
FROM Products p
INNER JOIN (select productid, count(*) as c from Sales group by productid) s 
   ON s.productId = p.productid
INNER JOIN (select productid, count(*) as c from ProductViews group by productid) v 
   ON p.productId = v.productid

如果您的产品没有销售或视图,则需要离开加入

答案 3 :(得分:0)

SELECT a.productid, a.name, a.price, (

SELECT COUNT( b.viewid ) 
FROM ProductViews b
WHERE b.productid = a.productid
) AS TotalViews, (

SELECT COUNT( c.salesid ) 
FROM Sales c
WHERE c.productid = a.productid
) AS TotalSales

FROM products a