2010-06-07 12 views
5

Necesito ayuda con una consulta MySQL. Tengo dos tablas, una con ofertas y otra con estados. Una oferta puede tener uno o más estados. Lo que me gustaría hacer es obtener todas las ofertas y su estado más reciente. Para cada estado hay un campo de tabla llamado 'agregado' que se puede usar para clasificar.Se necesita ayuda con una consulta SQL

Sé que esto se puede hacer fácilmente con dos consultas, pero tengo que hacerlo con una sola porque también tengo que aplicar algunos filtros más adelante en el proyecto.

Aquí está mi configuración:

CREATE TABLE `test`.`offers` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , 
`client` TEXT NOT NULL , 
`products` TEXT NOT NULL , 
`contact` TEXT NOT NULL 
) ENGINE = MYISAM ; 

CREATE TABLE `statuses` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
`offer_id` int(11) NOT NULL, 
`options` text NOT NULL, 
`deadline` date NOT NULL, 
`added` datetime NOT NULL, 
PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 

Respuesta

2

debería funcionar, pero en mi humilde opinión no es muy óptimo:

SELECT * 
FROM offers 
INNER JOIN statuses ON (statuses.offer_id = offers.id 
    AND statuses.id = 
      (SELECT allStatuses.id 
      FROM statuses allStatuses 
      WHERE allStatuses.offer_id = offers.id 
      ORDER BY allStatuses.added DESC LIMIT 1)) 
+0

sí, funciona. ¡Gracias! No sabía que podía escribir código adicional en ON(). – Psyche

0

Prueba esto:

SELECT 
o.* 
FROM offers o 
INNER JOIN statuses s ON o.id = s.offer_id 
ORDER BY s.added 
LIMIT 1 
Cuestiones relacionadas