For each identifier, how can I return the quantity when the received country is not equal to any of the delivered countries? I need an efficient query for the steps below since my table is huge.
These are the steps I would think could do this, of course you don’t need to follow them 🙂
- Create a group of ‘delivered’ countries for each identifier.
- See if ‘received’ is any of these countries for each identifier. If
there is no match, return this result.
Starting Table:
identifier delivered received quantity
------------- ------------ ----------- ------------
1 USA France 432
1 France USA 450
1 Ireland Russia 100
2 Germany Germany 1,034
3 USA France 50
3 USA USA 120
Result:
identifier delivered received quantity
------------- ------------ ----------- ------------
1 Ireland Russia 100
The starting table is about 30,000,000 rows, so self-joins will be impossible unfortunately. I am using something similar to MySQL.
I think
LEFT JOINquery should work for you:Example: SQLFiddle
For optimizing above query, adding following composite index should give you better performance: