MySQL присоединиться к таблице, даже если вторая таблица возвращает 0 запросов? - PullRequest
0 голосов
/ 24 декабря 2010

У меня есть такие данные:

table 1
|id|fieldname1|fieldname2|price|

table 2
|id|fieldname3|fieldname4|price|

desired result:
|table1_id|table2_id|fieldname1|fieldname2|fieldname3|fieldname4|table1_min_price|table2_min_price|

В принципе, я могу выполнить левое соединение из таблицы 1 в таблицу 2 (fieldname1 = fieldname3), получив самую низкую цену из каждой таблицы.

Однако, если таблица 2 вернет 0 запросов, результаты вообще не будут объединяться. Мое намерение состоит в том, чтобы, если у таблицы 2 или таблицы 1 не было результатов, она все равно объединит таблицу и создаст поля с нулевыми значениями.

Есть идеи, как это можно сделать?

Ответы [ 4 ]

1 голос
/ 28 декабря 2010

ИЗМЕНИТЬ 'СОЮЗ ВСЕХ' НА 'СОЮЗ':

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 

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)
1 голос
/ 24 декабря 2010

Вы можете захотеть FULL OUTER JOIN, который даст вам либо значения из таблицы 1, либо значения из таблицы 2 или оба. Но я не думаю, что вы можете получить ряд, когда его ни

0 голосов
/ 28 декабря 2010

Ниже таблица, которую я придумал.


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.Есть ли лучший способ?

0 голосов
/ 24 декабря 2010

вы можете выполнить полное внешнее соединение, как показано ниже:

select *
from table1 left outer join table2 on(fieldname1=fieldname3)
union 
select *
from table1 right outer join table2 on(fieldname1=fieldname3)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...