Answer the question
In order to leave comments, you need to log in
Is the sql query correct/optimal?
The query should return the top 10 selling products that are bought along with this product (for example, productID = 684).
Items that were in the cart (records remain even after placing an order), when adding a product to the cart, it receives a unique itemID i.e. the table contains productID = 684 with multiple itemIDs.
`SC_shopping_cart_items` (
`itemID` int(11) NOT NULL AUTO_INCREMENT,
`productID` int(11) DEFAULT NULL,
PRIMARY KEY (`itemID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
`SC_ordered_carts` (
`itemID` int(11) NOT NULL DEFAULT '0',
`orderID` int(11) NOT NULL DEFAULT '0',
`name` varchar(255) DEFAULT NULL,
`Price` float DEFAULT NULL,
`Quantity` int(11) DEFAULT NULL,
PRIMARY KEY (`itemID`,`orderID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
SELECT
COUNT(sci.productID) AS cnt,
sci.productID
FROM SC_shopping_cart_items sci
JOIN SC_ordered_carts oc ON oc.itemID = sci.itemID
WHERE sci.productID != 684 AND oc.orderID IN (
SELECT oc.orderID FROM SC_ordered_carts oc
JOIN SC_shopping_cart_items sci ON oc.itemID = sci.itemID
WHERE sci.productID = 684
) GROUP BY sci.productID ORDER BY cnt DESC LIMIT 10
Answer the question
In order to leave comments, you need to log in
Look better at the runtime, if it suits you, then everything is ok.
All the same structure of tables cannot be changed.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question