A
A
Anton Shamanov2015-07-13 16:33:33
MySQL
Anton Shamanov, 2015-07-13 16:33:33

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;

Items in orders, link to SC_shopping_cart_items by itemID field (1: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;

And my request itself:
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

PS The structure of the tables, alas, I can not change and I did not compose it either.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Lebedev, 2015-07-13
@swanrnd

Look better at the runtime, if it suits you, then everything is ok.
All the same structure of tables cannot be changed.

S
Stanislav Makarov, 2015-07-13
@Nipheris

EXPLAIN decides.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question