Relations:
Product( maker, model, type )
PC( model, speed, ram, hd, price)
Laptop( model, speed, ram, hd, screen, price)
Printer( model, color, type, price)
I am currently trying to teach myself MySQL for work. I bought a book and am going through some example problems. I have come to a halt trying to figure out how I might structure these queries.
- Find, for each different speed, the average price of a PC
- Find, for each manufacturer, the average screen size of its laptops
- Find the manufacturers that make at least three different models of pc
- Find, for each manufacturer who sells pc’s, the maximum price of a pc
- Find, for each speed of pc above 2.0, the average price
I can do the average of a column easily ” SELECT AVG(price) FROM pc ” but I am not sure how to do the for each x find its average of y. Problems 1,2,4,5 are are structured like this, problem 3 I think would have a subquery within it as such, that I think will find a relation with the model, maker of each pc in it. But I am not sure how to do the second part “maker makes at least three different models”
(SELECT model, maker FROM product NATURAL JOIN pc WHERE type = 'pc')
Any help? Thanks in advance!
1/ The for X is done by using a
GROUP BY:2/ is quite similar.. can you find it, after having read the GROUP BY Mysql Documentation?
Logic: Same is 1, but here we need the maker. So we need to add the columns from Product. We join product with laptop, and then we group by maker.
3/ is also group by, and you’ll want to use HAVING. Try it, ask in comments if you need more help or a solution.
Same as 2: join product with PC, now group by maker, now only keep the rows which have a count higher than three. You can indeed do this with a subquery too:
4/ will be a group by, and a join with product to get the maker
Care to try this one again? Your first proposed solution is:
even if two rows have the same highest value. The GROUP BY is a kind
of distinct, too.
subquery, think about which columns you need (do you need model?
Why?).
5/ is like 1, but with a WHERE-clause. No biggie.