Q (kdb): nested where query
Asked Answered
S

3

11

What are the ways to in Q to use the results of a nested query in a where clause?

I'm looking for something similar to SQL statement.

select from food where type_id in (
    select type_id from types where type_name = "fruit"
)
Solo answered 17/7, 2011 at 18:19 Comment(0)
A
7
select from food where type_id in (exec type_id from types where type_name like "fruit")

Your query was almost correct apart from what you passing to the in predicate and use the like function for string equality. You are passing a table when it only accepts a list. To send the query as a list I use exec which does the job.

Arbe answered 11/8, 2011 at 12:3 Comment(0)
W
6

while that's the direct answer to your question, the best way do this is probably foreign keys:

q)types:([type_id:`apple`orange`cucumber]type_name:`fruit`fruit`vegetable)
q)food:([type_id:`types$`apple`orange`cucumber]price:3?2.)
q)meta food
c      | t f     a
-------| ---------
type_id| s types  
price  | f        
q)select from food where type_id.type_name=`fruit
type_id| price    
-------| ---------
apple  | 0.4593231
orange | 1.383906 
q)
Wonderland answered 23/3, 2012 at 3:11 Comment(0)
P
3

Another way of doing it:

select from food where type_id in (select type_id from types where type_name like "fruit")[`type_id]
Polyhistor answered 20/7, 2017 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.