3表计数查询mysql
我有三张桌子3表计数查询mysql,sql,mysql,Sql,Mysql,我有三张桌子 products [which contains data related to products] productid (int) name (varchar) price (float) sales [which contains data related to sales] salesid (int) productid (int) time (datetime) links [which contains data rel
products [which contains data related to products]
productid (int)
name (varchar)
price (float)
sales [which contains data related to sales]
salesid (int)
productid (int)
time (datetime)
links [which contains data related to links from products]
linkid (int)
productid (int)
link (text)
我需要这样的输出
ProductID Name TotalSales TotalLinkAvailable
1 ABCD 10 12
1 EFGH 7 25
如何使用单个查询实现这一点
谢谢
编辑
我尝试了以下不起作用的查询:
select p.name,count(s.salesid) as Sales, count(l.linkid) as Links
from products p
left join sales s on p.productid=s.productid
left join links l on p.products=l.productid
group by p.productid
假设示例性查询结果的第二行中有关于ProductID的输入错误。With
JOIN
、groupby
和COUNT
。我现在懒得写查询。@Bobby:我尝试了以下查询选择p.name,count(s.salesid)作为Sales,count(l.linkid)由于来自产品p的链接通过p.productid=s.productid左连接销售s在p.products=l.productid上的链接通过p.productid左连接l在p.products=l.productid组但不起作用请始终在问题中告诉我们您已经尝试了什么,鲍比:下一次我一定会提到我所拥有的一切tried@I-M-JM-在您的示例中,您使用两个不同的名称列出了产品1。我刚刚添加了count(distinct(s.salesid)),它成功了,谢谢
select p.productid, p.name, count(s.salesid) as TotalSales, count(l.linkid) as TotalLinkAvailable
from products p
left join sales s
on p.productid = s.productid
left join links l
on p.productid = l.productid
group by p.productid, p.name
select p.pname,count(s.salesid) as Sales ,count(l.linkid) as Links
from products p left join sales s on p.productid=s.productid
left join links l on p.products=l.productid
group by p.productid
SELECT p.productid AS ProductID, p.name AS Name, COUNT(s.salesid) AS TotalSales, COUNT(l.linkid) AS TotalLinkAvailable
FROM products AS p
LEFT JOIN sales AS s ON s.productid = p.productid
LEFT JOIN links AS l ON l.productid = p.productid
GROUP BY p.productid, p.name