I have four tables in a database. the tables are like the following:
Cashier(cashier_id*, cashier_name)
Category(category_id*, category_name)
Product(product_id*, product_name, price, category_id**)
Purchase(product_id**, cashier_id**, amount)
* primary key
** foreign key
I want to select category name with the highest number of purchase. Here's what I've done so far, but I couldn't get the result that i want
SELECT x.category,x.amount
FROM (SELECT category_name as category, SUM(amount) as amount FROM
Category c, Product pr, Purchase pu WHERE pr.product_id =
pu.product_id and c.category_id = pr.category_id GROUP BY
category_name) x
GROUP BY x.category
HAVING MAX(x.amount);
Presumably, you want something like this:
SELECT c.category_name as category, SUM(amount) as amount
FROM Category c JOIN
Product pr
ON c.category_id = pr.category_id JOIN
Purchase pu
ON pr.product_id = pu.product_id
GROUP BY category_name
ORDER BY SUM(amount) DESC
LIMIT 1;
Never use commas in the FROM
clause. Always use proper, explicit, standard JOIN
syntax.