how to apply limit with union in Mysql

how to apply limit with union in Mysql query ?

We have a condition that we want to fetch some data from different tables and combined them with onion in Mysql . Which is very simple we can do this :

Query 1

union

Query 2

union

Query 3

and so on …

but in above queries if we want to apply the limit, than it will give error .

here we will discussing what we can do to achieve the results.

If  we have multiple query set than how can we use limit and union them all ?

we can do this by separating the query set with () – brackets and merge them with union in mysql , For example we have two tables :-

Table T1

IDNameCity
1SandyAgra
2RajBareilly
3DeepakMeerut
4SurajNainital

Table T2

IDNameCity
5SitaRamgarh
7GeetaDehradoon
8SunilRamnagar
9SonaDelhi

(SELECT name,city FROM T1 WHERE id < 3  LIMIT 1)
UNION
(SELECT name,city FROM T2 WHERE  ORDER BY id desc LIMIT 3);

If we do this above like this :-

SELECT name,city FROM T1 WHERE id < 3  LIMIT 1
UNION
SELECT name,city FROM T2 WHERE  ORDER BY id desc LIMIT 3

Than it will give error ……

How to get random data in Mysql

check for the documentation

Leave a Reply

Your email address will not be published. Required fields are marked *