问题
I understand that BigQuery supports merging two tables. Currently, the INSERT
operation allows inserting explicit values into a table, such as
INSERT dataset.Inventory (product, quantity)
VALUES('top load washer', 10),
('front load washer', 20),
('dryer', 30),
('refrigerator', 10),
('microwave', 20),
('dishwasher', 30),
('oven', 5)
Is there a way to do something similar with the MERGE
operation? For example, something like:
MERGE dataset.DetailedInventory T
USING('top load washer', 10),
('front load washer', 20),
('dryer', 30),
('refrigerator', 10),
('microwave', 20),
('dishwasher', 30),
('oven', 5)
ON T.appliance = [I don't know what would go here]
WHEN NOT MATCHED THEN [insert]
WHEN MATCHED THEN [update]
I'm relatively new to GBQ and SQL, so my apologies if this is a simple question to answer.
回答1:
You can use a subquery:
MERGE dataset.DetailedInventory T
USING (SELECT 'top load washer' as col1, 10 as col1 UNION ALL
SELECT 'front load washer', 20 UNION ALL
SELECT 'dryer', 30 UNION ALL
SELECT 'refrigerator', 10 UNION ALL
SELECT 'microwave', 20 UNION ALL
SELECT 'dishwasher', 30 UNION ALL
SELECT 'oven', 5
) src
ON T.appliance = src.col1
WHEN NOT MATCHED THEN [insert]
WHEN MATCHED THEN [update]
回答2:
Consider below version using BigQuery Scripting - I think this is the closest possible to what you are looking for
CREATE TEMP TABLE inventoryUpdates (product STRING, quantity INT64);
INSERT inventoryUpdates
VALUES ('top load washer', 11),
('front load washer', 20),
('dryer', 30),
('refrigerator', 11),
('microwave', 20),
('dishwasher', 30),
('oven', 5);
MERGE `dataset.Inventory` T
USING inventoryUpdates U
ON T.product = U.product
WHEN NOT MATCHED THEN
INSERT (product, quantity) VALUES(product, quantity)
WHEN MATCHED THEN
UPDATE SET quantity = T.quantity + U.quantity;
来源:https://stackoverflow.com/questions/63180227/bigquery-merge-using-explicit-values