Проблема в том, что три ноги в UNION всегда будут разными из-за разных констант для литерала {city, state, driver, truck}. Таким образом, дубликатов не будет, и UNION
даст тот же результат, что и UNION ALL
.
Пример:
-- some data ...
CREATE TABLE one
( num integer not null
, nam text
);
INSERT INTO one ( num , nam ) values (1,'one'), (2, 'two'), (3, 'three');
-- QUERY#1
SELECT 'from_first' AS "origin"
, num, nam
FROM one
UNION
SELECT 'from_second' AS "origin"
, num, nam
FROM one
ORDER BY 1,2
;
-- QUERY#2
SELECT 'from_first' AS "origin"
, num, nam
FROM one
UNION ALL
SELECT 'from_second' AS "origin"
, num, nam
FROM one
ORDER BY 1,2
;
Результаты:
CREATE TABLE
INSERT 0 3
origin | num | nam
-------------+-----+-------
from_first | 1 | one
from_first | 2 | two
from_first | 3 | three
from_second | 1 | one
from_second | 2 | two
from_second | 3 | three
(6 rows)
origin | num | nam
-------------+-----+-------
from_first | 1 | one
from_first | 2 | two
from_first | 3 | three
from_second | 1 | one
from_second | 2 | two
from_second | 3 | three
(6 rows)
Ситуация отличается, когда один или два из подвыборов дают дубликаты, например:
-- some more data ...
CREATE TABLE two
( num integer not null
, nam text
);
INSERT INTO two ( num , nam ) values (1,'one'), (2, 'two'), (2, 'two');
-- QUERY#1a
SELECT 'from_first' AS "origin"
, num, nam
FROM two
UNION
SELECT 'from_second' AS "origin"
, num, nam
FROM two
ORDER BY 1,2
;
-- QUERY#2b
SELECT 'from_first' AS "origin"
, num, nam
FROM two
UNION ALL
SELECT 'from_second' AS "origin"
, num, nam
FROM two
ORDER BY 1,2
;
Results2:
CREATE TABLE
INSERT 0 3
origin | num | nam
-------------+-----+-----
from_first | 1 | one
from_first | 2 | two
from_second | 1 | one
from_second | 2 | two
(4 rows)
origin | num | nam
-------------+-----+-----
from_first | 1 | one
from_first | 2 | two
from_first | 2 | two
from_second | 1 | one
from_second | 2 | two
from_second | 2 | two
(6 rows)