I'm trying to solve Exercise 25 from sql-ex.ru:
The database scheme consists of four tables:
- Product(maker, model, type)
- PC(code, model, speed, ram, hd, cd, price)
- Laptop(code, model, speed, ram, hd, screen, price)
- Printer(code, model, color, type, price)
Find the printer makers also producing PCs with the lowest RAM capacity and the highest processor speed of all PCs having the lowest RAM capacity. Result set: maker.
I can't see why the following query does not produce the desired result on the second checking database:
SELECT DISTINCT product.maker
FROM product
RIGHT JOIN printer ON printer.model = product.model
WHERE product.maker IN(
SELECT product.maker
FROM product
RIGHT JOIN pc ON pc.model = product.model
WHERE pc.ram = (SELECT MIN(ram) FROM pc)
AND pc.speed = (
SELECT MAX(t.speed)
FROM (SELECT speed FROM pc WHERE ram = (SELECT MIN(ram) FROM pc)) AS t
)
)
The error is as follows:
Wrong
Your query produced correct result set on main database, but it failed test on second, checking database
* Wrong number of records (less by 1)
Why does it fail to pick exactly 1 maker?
I do not know where is the error in your query, but you can use something like this:
WITH t AS ( SELECT * FROM PC c WHERE c.ram = (SELECT MIN(ram) FROM PC) ) SELECT DISTINCT a.maker FROM Product a WHERE a.type = 'PC' AND a.maker IN ( SELECT b.maker FROM Product b WHERE b.type = 'Printer' ) AND a.model IN ( SELECT model FROM t WHERE speed = (SELECT MAX(speed) FROM t) )
Here's the solution to this problem:
WITH CTE_Product AS
(
SELECT DISTINCT
Maker
FROM
Product
WHERE
Type = 'PC'
AND
Maker IN (SELECT Maker FROM Product WHERE Type = 'Printer')
)
select c.maker from CTE_Product C
inner join
(
select distinct maker from product inner join PC on product.model=pc.model
where type='PC'and
pc.speed in
(select max(speed)
from pc
where ram=
(select min(ram)from pc)
)
and pc.ram=
(select min(ram)
from pc)
) A on A.maker = C.maker
SELECT DISTINCT maker
FROM Product
WHERE TYPE = 'Printer'
INTERSECT
SELECT DISTINCT maker
FROM Product AS p
INNER JOIN PC as pc
ON p.model = pc.model
WHERE
type = 'PC'
AND (pc.ram = ALL (SELECT MIN(ram) FROM PC))
AND (pc.speed = (SELECT MAX(speed) FROM PC WHERE ram = (SELECT MIN(ram) FROM PC )))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.