You can get this to work in a single query. However it is going to be sub-optimal, because for each item in data1 you would need to check three conditions, which potentially require going through the entire data2 for an O(m*n) time complexity (space complexity remains O(1), though).