1

I have 3 tables

products
    productid (int)
    name (varchar)
    price (float)

sales
    salesid (int)
    productid (int)
    time (datetime)

links
    linkid (int)
    productid (int)
    link (text)

Now I need a query that can display as

ProductID      ProductName      Sales      Links
    1           ABC               10        8
    2           XYZ               15       12

I need all sales count and all links count for a particular product

How can I achieve this?

Thanks

1
  • What's this for, out of curiosity? Commented Dec 10, 2010 at 12:57

3 Answers 3

3
SELECT p.productid, p.pname AS ProductName, 
       Count(DISTINCT s.salesid) as Sales, Count(DISTINCT 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
Sign up to request clarification or add additional context in comments.

2 Comments

What do you mean by "count same"? Do you mean the Sales and Links columns show the same count in each row?
for first join, if it is left join then count come same
0

You need to write a cross-tab query.

This walk-through on the mysql site should help.

Or like in this tutorial

2 Comments

I've added a link to how the official mysql site solves this type of problem - that one is definitely optimized.
Cross tab queries are to convert data in rows into columns. OP needs data aggregation, not a cross tab.
0

You can only use aggregate functions (like Count()) on the column specified in the GROUP BY clause, otherwise the aggregation is ambiguous. See the chapter "Ambiguous Groups" from the excellent book SQL Antipatterns for more reference.

In your case, the best option is to use two sub-queries:

SELECT p.productid as ProductID, p.pname AS ProductName, 
        (SELECT Count(*) FROM sales s WHERE p.productid=s.productid) as Sales,
        (SELECT Count(*) FROM links l WHERE p.productid=l.productid) as Links,
    FROM products p
    GROUP BY p.productid

Not the most efficient query ever written, but it's perfectly ok as long as the tables doesn't contain a huge number of rows and/or you run it as a periodic report and not real-time on live data.

The best thing to do is to test it for yourself and see if the performance is acceptable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.