|
我正在尝试搜索在数组中具有某些键值对的行。我的BigQuery表中的一行看起来像这样。9 B( w9 W! S0 i+ R5 ?8 B
{# T0 g" N& F( W: F( A
"ip": "192.168.1.1",
7 J& ~( P2 w. d0 { "cookie" [* v/ p# C! k- I3 I4 Y
{
( L+ n2 w3 ]1 Z8 B) E6 l "key": "apple",
6 X, W( W( S3 e$ f+ q& ?6 A: x "value: "red"
5 i2 e, C# H& R' J) h },
! ]) l& `2 _2 I$ `' v {
+ g9 X: ^4 @6 |+ @: P# p "key": "orange",
4 S8 t; r8 B+ [, w' q) T "value: "orange"
) g8 H' h, j/ Y1 O+ o T },
2 r" ~( c" n8 \' M, s% h" v7 ~ {7 i) R9 I9 L+ O3 b O: t8 j- D; |/ M! H
"key": "grape",5 R4 S% ?0 S5 _6 c0 a# [
"value: "purple"
3 x3 H) B$ s. ^. U D }3 O: f9 K* U. f$ @7 y |8 B7 m
]
% d: @3 |# |: z! }+ @}2 I8 [5 E" e' k1 K. l4 H, h
我考虑过使用隐式UNNEST或CROSS JOIN,如下所示,但是它没有用,因为取消嵌套只会创建多个不同的行。
3 s0 V7 H' k8 W. \7 p2 W# cSELECT ip
: j2 ^' h7 M" j. y5 b2 ^; eFROM table t, t.cookie c
0 e; Q" v3 d; c- ~WHERE (c.key = "grape" AND c.value ="purple") AND (c.key = "orange" AND c.value ="orange")# }6 V5 C8 O" Y" Q# A$ w( I
这个链接真的很接近我想要做的,除了他们正在使用legacy SQL而不是正在使用standardSQL
8 _9 ^4 A; c# {" J
9 N& s ^( v5 F# T U) y6 k解决方案:" S2 B5 M1 P7 u, H
( }# Y {0 e3 I# h
5 ~" f5 k3 r) S: g8 r: i1 q& O# _0 B
; f5 E0 y; f/ s; v; G; H
standardSQL
+ P( r i4 L' p5 PSELECT ip, m) i0 B2 `& \. Q
FROM yourTable % f+ K* N. X+ k' ~
WHERE (3 x" H5 q% u3 X0 O( f
SELECT COUNT(1)
$ l/ A. J7 G6 f' ]! J FROM UNNEST(cookie) AS pair 3 z- f: |, j) W( Y
WHERE pair IN (('grape', 'purple'), ('orange', 'orange'))
& k/ N5 l2 H2 j5 E) >= 2
C, V' e, Y5 F5 v/ I- l7 ^+ R您可以使用下面的虚拟数据进行测试# Y0 k5 i; O9 E+ g: e+ f
#standardSQL
& q2 I; R; j0 AWITH yourTable AS (9 E, s) g: g, i* `7 M; k) ~
SELECT '192.168.1.1' AS ip, [('apple', 'red'), ('orange', 'orange'), ('grape', 'purple')] AS cookie UNION ALL( a E* T) X3 z6 ?0 \
SELECT '192.168.1.2', [('abc', 'xyz')]
# n8 i6 X& H( U: O, ~1 r)
* k/ w9 l3 ~' p- P, q9 FSELECT ip5 D1 w0 q1 ^7 q
FROM yourTable
V8 m* a- ^8 I( x4 O2 v( |1 _WHERE (
+ x0 X8 Z; U! b* P5 W* J SELECT COUNT(1)
. ?' u/ T9 X0 ^ FROM UNNEST(cookie) AS pair
" a4 [" b; }$ T, @* O7 R8 n WHERE pair IN (('grape', 'purple'), ('orange', 'orange')), t- v& H& g8 u1 Z a0 u
) >= 2* j2 b% ^- r, Z0 W. h( s' {
如果在阵列中至少有一对时需要输出ip,则需要更改>= 2为>=1inWHERE子句 |
|