数据操作语言(DML)语句

BigQuery 入门

Matt Forrest

Field CTO

BigQuery 中的数据操作概览

  • INSERT:添加新行。
  • UPDATE:修改现有行中的值。
  • DELETE:从表中删除不需要的数据。
  • MERGE:将 INSERTUPDATEDELETE 合并为一条语句。
  • CREATE TABLE AS:根据查询结果创建新表。
BigQuery 入门

注意事项与性能

  • 尽量将 DML 语句批量执行,而非逐条运行
  • 运行 UPDATE 时必须包含 WHERE 条件
  • 考虑使用分区和聚簇表
1 https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language
BigQuery 入门

INSERT

  • 向表添加记录
-- Define the columns in the parentheses 
INSERT INTO customers (customer_id, name, email)

-- Each value is a row to be inserted
VALUES (1, "John Doe", "[email protected]"),
(2, "Jane Doe", "[email protected]"),
(3, "Alice Smith", "[email protected]");
BigQuery 入门

UPDATE

  • 基于条件修改数据
UPDATE customers
-- Set one column for each SET statement
SET email = "[email protected]"
-- Make sure to include where otherwise all
-- rows will be updated
WHERE customer_id = 1;
  • UPDATE 与子查询或连接一起使用
    UPDATE customers c
    SET c.email = e.email
    FROM emails e
    WHERE c.customer_id = 1;
    
BigQuery 入门

DELETE

  • DELETE 会永久删除记录,且不可撤销
DELETE FROM customers

-- Include WHERE to ensure only specific rows are deleted
WHERE customer_id = 3;
DELETE FROM customers c
JOIN emails e USING (customer_id)
WHERE email = '[email protected]'
BigQuery 入门

MERGE

  • 在一次操作中组合 INSERTUPDATEDELETE
-- Sets the customers table as the target
MERGE customers AS target

-- The source is set to new_customers USING new_customers AS source
-- Matching condition ON target.customer_id = source.customer_id
-- If the emails do not match, update the email WHEN MATCHED AND target.email != source.email THEN UPDATE SET email = source.email
-- If the match is not met, insert the record WHEN NOT MATCHED THEN INSERT (customer_id, name, email) VALUES (source.customer_id, source.name, source.email);
BigQuery 入门

CREATE TABLE

  • 通过查询创建新表
CREATE TABLE active_customers AS
SELECT customer_id, name, email 
FROM customers
WHERE last_active_date > DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY);
BigQuery 入门

Vamos praticar!

BigQuery 入门

Preparing Video For Download...