【问题标题】:Insert into table two and update table two for BigQuery in one query在一个查询中插入表 2 并更新 BigQuery 的表 2
【发布时间】:2019-12-07 03:16:31
【问题描述】:

我在 BigQuery 中使用 StandardSQL。我正在编写一个预定查询,它将记录插入到表 (2) 中。现在,鉴于它已调度,我试图弄清楚如何从调度查询更新表 (2) 中的记录,该查询始终将记录插入表 (2)。

特别是,当表 (2) 中有记录但不是由我的查询生成时,我想将表 (2) 和布尔列更新为否。

下面是我的查询,我应该在查询的哪个位置添加表 (2) 的更新逻辑?


INSERT INTO record (airport_name, icao_address, arrival, flight_number, origin_airport_icao, destination_airport_icao)


WITH
  planes_stopped_in_airport AS (
  SELECT
    p.IATA_airport_code,
    p.airport_name,
    p.airport_ISO_country_code,
    p.ICAO_airport_code,
    timestamp,
    a.icao_address,
    a.latitude,
    a.longitude,
    a.altitude_baro,
    a.speed,
    heading,
    callsign,
    source,
    a.collection_type,
    vertical_rate,
    squawk_code,
    icao_actype,
    flight_number,
    origin_airport_icao,
    destination_airport_icao,
    scheduled_departure_time_utc,
    scheduled_arrival_time_utc,
    estimated_arrival_time_utc,
    tail_number,
    ingestion_time
  FROM
    `updates` a
  JOIN
    Polygons p
  ON
    1 = 1
  WHERE
   a.timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 20 MINUTE) and a.timestamp <= CURRENT_TIMESTAMP()
    AND ( latitude IS NULL
      AND longitude IS NULL
      AND callsign IS NULL
      AND speed IS NULL
      AND heading IS NULL
      AND altitude_baro IS NULL) IS FALSE
    AND ST_DWithin( ST_GeogFromText( polygon ),
      ST_GeogPoint(a.longitude,
        a.latitude),
      10)
    AND a.collection_type = '1' -- and speed < 50
    AND (origin_airport_icao IS NULL
    AND destination_airport_icao IS NULL) IS FALSE )
SELECT
  p.airport_name,
  icao_address,
  MIN(timestamp) AS Arrival,
  flight_number,
  origin_airport_icao,
  destination_airport_icao
FROM
  planes_stopped_in_airport p
WHERE 
  flight_number NOT IN (SELECT Distinct flight_number
                        FROM `table(2)`                                               
                        )
GROUP BY
  icao_address,
  p.airport_name,
  flight_number,
  origin_airport_icao,
  destination_airport_icao
HAVING
  flight_number IS NOT NULL
ORDER BY
  airport_name,
  arrival

【问题讨论】:

    标签: insert google-bigquery sql-update


    【解决方案1】:

    您可能可以使用 MERGE 语句来完成,请参阅https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement 中的详细信息。

    如果我正确理解了您的要求,您需要类似的东西

    MERGE dataset.Destination T
    USING (SELECT * ...) S
    ON T.key = S.key
    WHEN MATCHED THEN
      UPDATE SET T.foo = S.foo, T.bool_flag = FALSE
    WHEN NOT MATCHED THEN
      INSERT ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      • 2013-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多