KDB:如何使用一组列进行查询

时间:2019-01-24 15:45:39

标签: kdb

如何执行相应的SQL查询:

select * from a where (col1, col2) in (select x, y from b)

如果我有

p:([]name:`John`Mary`David`James; age:52 49 18 23; hair:("black";"black";"blonde";"black"); eyes:`brown`brown`blue`brown; aa:("hello";"world";"hi";"there"))

如何使此查询起作用:

select from p where (hair, eyes) in (
select hair, eyes from p where any aa like/:("hello";"hi")
)

3 个答案:

答案 0 :(得分:2)

select hair, eyes from p where any aa like/:("hello";"hi")的输出是一个表,因此我们需要使用haireyes列中的表来创建所需的where语句:

q)select from p where ([]hair;eyes) in select hair, eyes from p where any aa like/:("hello";"hi")
name  age hair     eyes  aa
--------------------------------
John  52  "black"  brown "hello"
Mary  49  "black"  brown "world"
David 18  "blonde" blue  "hi"
James 23  "black"  brown "there"

答案 1 :(得分:2)

您也可以使用fby

q)select from p where (any;any aa like/:("hello";"hi")) fby ([]hair;eyes)
name  age hair     eyes  aa
--------------------------------
John  52  "black"  brown "hello"
Mary  49  "black"  brown "world"
David 18  "blonde" blue  "hi"
James 23  "black"  brown "there"

fby允许您基于特定分组应用聚合,然后基于这些聚合进行过滤。在这种情况下,提供的某些其他解决方案可能更具可读性,但是fby是一个功能强大的工具,可以帮助避免在很多实例中使用嵌套的select语句

答案 2 :(得分:1)

其他选择是使用等联接(ej):

 q) ej[`hair`eyes;select from p where any aa like/:("hello";"hi");p]
name  age hair     eyes  aa
--------------------------------
John  52  "black"  brown "hello"
Mary  49  "black"  brown "world"
James 23  "black"  brown "there"
David 18  "blonde" blue  "hi"

请注意,这将按用于相等性的列对结果进行排序。在此示例中,按头发,眼睛列。因此该顺序可能与表中行的实际顺序不同。

在此处了解有关ej的信息:https://code.kx.com/q/ref/joins/#ej-equi-join