简体   繁体   中英

SQL - Accessing only the first row of a struct value in a specific column

here is the format of my table.

custom_fields RECORD REPEATED
custom_fields. value RECORD NULLABLE
custom_fields.value. name STRING NULLABLE
custom_fields.value. value STRING NULLABLE

I want to access to "custom_fields.value.name". I tried:

SELECT * from [my_database] 
WHERE custom_fields.value.name = "something";

Cannot access field value on a value with type ARRAY<STRUCT<value STRUCT<name STRING, value STRING>>> at [1:78]

I may work with another table because I feel that the format is really tough to work easily with. But I will appreciate your ideas on this problem.

Thanks

Arrays are available in very few databases. But in those that do, you would need to index the array. The error message looks like BigQuery.

If you want to look at the first value, then you would use:

SELECT * 
FROM [my_database] 
WHERE custom_fields[SAFE_ORDINAL(1)].value.name = 'something';

If you wanted to return rows where any value matches, then use UNNEST() in the WHERE clause:

SELECT * 
FROM [my_database] 
WHERE EXISTS (SELECT 1 FROM UNNEST(custom_fields) cf WHERE cf.value.name = 'something');

If you wanted only the elements from customer_fields that match, then move the UNNEST() to the FROM`:

SELECT t.* EXCEPT (customer_fields), cf 
FROM [my_database] t CROSS JOIN
     UNNEST(custom_fields) cf
WHERE cf.value.name = 'something');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM