2010-12-10 65 views
1

我有3個表3臺數查詢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 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 
+0

使用'JOIN','GROUP BY'和'COUNT'。我只是懶得寫現在的查詢。 – Bobby 2010-12-10 12:58:41

+0

@Bobby:我試過以下查詢select p.name,count(s.salesid)as Sales,count(l.linkid)as鏈接 from產品p left join sales s on p.productid = s.productid left join links l on p.products = l.productid group by p.productid,但它不起作用 – 2010-12-10 12:59:55

+0

請務必在問題中告訴我們您已經嘗試了什麼,它可以幫助您儘可能多地幫助您。 – Bobby 2010-12-10 13:13:37

回答

0
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 

假設有一個在示例性查詢結果的第二行中關於ProductID的拼寫錯誤。

+0

類型的意思,請解釋一下嗎? – 2010-12-10 13:20:15

+1

@ I-M-JM - 在您的示例中,您將列出帶有2個不同名稱的產品1。 – JNK 2010-12-10 14:02:02

+0

@ I-M-JM:* typo *(「打字錯誤」),而不是* type *。 – Flinsch 2010-12-12 17:06:36

0
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 
+0

錯誤計數是兩遍 – 2010-12-10 13:18:04

0
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