Ниже таблица, которую я придумал.
CREATE TABLE IF NOT EXISTS `farestable_test` (
`id` tinyint(4) NOT NULL,
`origin` varchar(3) NOT NULL,
`destination` varchar(3) NOT NULL,
`flight_type` tinyint(4) NOT NULL,
`price` float NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
SELECT * from
(SELECT origin,destination,min(price) as oneway_cheapest FROM farestable_test where flight_type=0 group by origin,destination )as t1
LEFT JOIN
(SELECT origin,destination,min(price) as return_cheapest FROM farestable_test where flight_type=1 group by origin,destination )as t2
ON (t1.origin = t2.origin AND t1.destination=t2.destination)
UNION ALL
SELECT * from
(SELECT origin,destination,min(price) as oneway_cheapest FROM farestable_test where flight_type=0 group by origin,destination )as t1
RIGHT JOIN
(SELECT origin,destination,min(price) as return_cheapest FROM farestable_test where flight_type=1 group by origin,destination )as t2
ON (t1.origin = t2.origin AND t1.destination=t2.destination)
Что я хочу достичь:
Если данные
INSERT INTO `farestable_test` (`id`, `origin`, `destination`, `flight_type`, `price`) VALUES
(1, 'syd', 'mky', 0, 100),
(2, 'syd', 'mky', 0, 200),
Это показывает ПРАВИЛЬНЫЕ результаты:
origin destination oneway_cheapest origin destination return_cheapest
syd mky 100 null null null
ИTHEN ....
Если данные
INSERT INTO `farestable_test` (`id`, `origin`, `destination`, `flight_type`, `price`) VALUES
(3, 'syd', 'mky', 1, 300),
(4, 'syd', 'mky', 1, 400);
Это покажет ПРАВИЛЬНЫЙ результат:
origin destination oneway_cheapest origin destination return_cheapest
null null null syd mky 300
Однако, если данные ниже
INSERT INTO `farestable_test` (`id`, `origin`, `destination`, `flight_type`, `price`) VALUES
(1, 'syd', 'mky', 0, 100),
(2, 'syd', 'mky', 0, 200),
(3, 'syd', 'mky', 1, 300),
(4, 'syd', 'mky', 1, 400);
Результат здесь НЕПРАВИЛЬНЫЙ:
origin destination oneway_cheapest origin destination return_cheapest
syd mky 100 syd mky 300
syd mky 100 syd mky 300
Он содержит дубликаты данных, что неверно, я не могу выполнить полное объединение без объединения всех с mysql.Есть ли лучший способ?