0

He probado con

SELECT nombre, categoria_id , precio FROM libro WHERE precio=(SELECT MAX(precio) FROM libro);

Pero solo me aparece el libro mas caro

2

2 respuestas 2

2

Puedes hacerlo sin usar subqueries utilizando Window Function desde MySql 8.0:

SELECT DISTINCT categoria_id,
       FIRST_VALUE(nombre) OVER (PARTITION BY categoria_id ORDER BY precio DESC) AS nombre,
       FIRST_VALUE(precio) OVER (PARTITION BY categoria_id ORDER BY precio DESC) AS precio
FROM libro 
ORDER BY categoria_id;

Si quieres utilizar una subquery sería así:

SELECT *
FROM libro
WHERE (categoria_id, precio) IN (SELECT categoria_id, MAX(precio)
                                 FROM libro
                                 GROUP BY categoria_id);

También puedes hacer un JOIN con la subquery que tiene los precios máximos por categoría:

SELECT l.*
FROM libro l
INNER JOIN (SELECT categoria_id, MAX(precio) AS precioMax
           FROM libro
           GROUP BY categoria_id) AS s ON l.categoria_id = s.categoria_id AND l.precio = s.precioMax;
2
0

Tines que incluir a tu tabla categoria con un INNER JOIN o LEFT JOIN en este caso si ya te muestra el libro mas caro deberia ser algo asi :

Select p.nombre,c.nombrecategoria,p.precio from libro p left join categoria c on c.idcategoria_id=p.idcategoria_id where p.precio =(select max(p.precio));

me comentas como te va.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.