Select unrelated columns from two unrelated tables
-
20-12-2019 - |
Question
Is there an easy way to select two columns from two unrelated tables, in order to use those columns in an insert?
Disclaimer: Ideally, I would never need to do this because the schema would have been set up with a little something called "foreign keys" and "referential integrity". But, it seems as though neither of these concepts existed on the planet on which this schema was created.
Here's a simplified version of what I need to do:
Customer Table
Id Name
------------
1 Eddie
2 Stone
3 Mike
Product Table
Id Name
---------------------
100 Drum sticks
101 Guitar strings
102 Amplifier
Invoice Table
Id CustomerName ProductName
---------------------------------------
1000 Eddie Guitar Strings
1001 Mike Amplifier
In my SQL code, I've got a :CustomerId
and a :ProductId
, and ideally I'd like to do something like this:
INSERT Invoice (
Id,
CustomerName,
ProductName
)
SELECT
:InvoiceId,
Customer.Name,
Product.Name
FROM
Customer,
Product
WHERE
Customer.CustomerId = :CustomerId
and Product.ProductId = :ProductId
This works fine and dandy if both the Customer and Product records exist, but I need to also cater for the scenario where one of them doesn't exist. (Yes, really.)
The only way I can think to do it is by declaring variables like :CustomerName
and :ProductName
and pre-populating them outside of the insert statement.
Is there a way to achieve this without going down the extra variables approach?
Solution
You could do this:
INSERT Invoice (
Id,
CustomerName,
ProductName
)
SELECT
:InvoiceId,
(
SELECT
Customer.Name
FROM
Customer
WHERE
Customer.CustomerId = :CustomerId
),
(
SELECT
Product.Name
FROM
Product
WHERE
Product.ProductId = :ProductId
)
FROM RDB$DATABASE
OTHER TIPS
Next to the answer provided by Arion, you could use a FULL OUTER JOIN
with a join condition that is always true. This only works correctly if both subqueries produce a single row.
SELECT
:InvoiceId,
CustomerName,
ProductName
FROM (
SELECT CustomerName
FROM Customer
WHERE CustomerId = :CustomerId
) a
FULL OUTER JOIN (
SELECT ProductName
FROM Product
WHERE Product.ProductId = :ProductId
) b
ON 1 = 1