In TiDB, how can I execute the same SELECT statement for every element of a set and union the results?
E.g. suppose I have this query which takes given_id
and returns <= 3 id
s:
SELECT id
FROM my_table
WHERE id > given_id
ORDER BY id
LIMIT 3;
How do I execute this query for every given_id
in a set of given_ids
?
In pseudocode, this would be like:
results = set()
for given_id in given_ids:
results += run_sql("""
SELECT id
FROM my_table
WHERE id > %s
ORDER BY id
LIMIT 3;
""" % given_id)
I'm aware of the UNION
keyword, but IIUC to use it you need to construct an expression with size linear in the number of given_id
s, which seems bad.
Is this something which requires defining SQL functions?
EDIT: Thanks to Tim Biegeleisen for giving an answer that uses the particular logic of the example query to solve the problem. BUT, I'm wondering if there is a general way to execute a parameterized SELECT statement on a set of inputs and then union the result.