[英]Select unrelated columns from two unrelated tables
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: 这是我需要做的简化版本:
Id Name
------------
1 Eddie
2 Stone
3 Mike
Id Name
---------------------
100 Drum sticks
101 Guitar strings
102 Amplifier
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: 在我的SQL代码中,我有一个
:CustomerId
和a :ProductId
,理想情况下我想做这样的事情:
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. 我能想到的唯一方法是声明变量,如
:CustomerName
和:ProductName
并在insert语句之外预先填充它们。
Is there a way to achieve this without going down the extra variables approach? 有没有办法实现这一点,而不采取额外的变量方法?
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
Next to the answer provided by Arion, you could use a FULL OUTER JOIN
with a join condition that is always true. 在Arion提供的答案旁边,您可以使用
FULL OUTER JOIN
,其连接条件始终为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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.