Re: Database efficiency question
Posted by: Rick James
Date: January 08, 2011 10:38AM

Yes.
You will probably have more columns in Product and Customer; they will have more information about the products and customers.

Customer_products will need indexes on prod_id and cust_id for efficiency in doing JOINs in each direction ("what products does this customer have" and "which customers have this product")

What products does customer 123 have:
SELECT c.cust_name, p.prod_name
    FROM Customers AS c
    JOIN Customer_Product AS cp  ON c.cust_id = cp.cust_id
    JOIN Products AS p  ON p.prod_id = cp.prod_id
    WHERE cust_id = 123;

To do that by cust_name instead of id, you should have INDEX(cust_name) (for efficiency), then do
SELECT c.cust_name, p.prod_name
    FROM Customers AS c
    JOIN Customer_Product AS cp  ON c.cust_id = cp.cust_id
    JOIN Products AS p  ON p.prod_id = cp.prod_id
    WHERE cust_id = 'Denis K';

To get fancier...
SELECT c.cust_name, GROUP_CONCAT(p.prod_name)
    FROM Customers AS c
    JOIN Customer_Product AS cp  ON c.cust_id = cp.cust_id
    JOIN Products AS p  ON p.prod_id = cp.prod_id
    GROUP BY c.cust_name;
should list all the products for each customer, one line per customer.

Options: ReplyQuote


Subject
Written By
Posted
January 04, 2011 10:46PM
January 06, 2011 09:11PM
January 07, 2011 11:18PM
January 08, 2011 12:59AM
January 08, 2011 10:02AM
Re: Database efficiency question
January 08, 2011 10:38AM
January 08, 2011 11:02AM
January 16, 2011 03:30PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.