Mysql – Extract N rows from 2 tables (t1, t2) – if t1 doesn’t match N rows, then (and only then) extract data from t2

MySQLquery

I would like to extract 100 names from table t1 and t2 where id = 'value', in such a way so that if table t1 hasn't 100 names, I will then go and take the remaining names from table t2.

The first part of the query would be (for table t1)

SELECT distinct name, id
FROM t1 WHERE id = 'value' 
ORDER BY id 
LIMIT 100;

Best Answer

You should be able to do this by using a union to join the two queries together. This assumes that Origin is a value that signifies which table is being queried so that results from t1 take precedence.

SELECT 1 as origin, name, id

FROM t1 WHERE id = 'value' 

union

SELECT 2 as origin, name, id

FROM t2 WHERE id = 'value' 

ORDER BY origin, id 

LIMIT 100