Question

I need to get the result from 2 tables with limit total 10


eg 1:
If I table_1 and table_2 have 15 records, my result will be 20:

SELECT * FROM table_1 limit 10 
UNION ALL 
SELECT * FROM table_2 limit 10 


eg 2:
table_1 if I have 3 records and records table_2 20, my result will be 8:

SELECT * FROM table_1 limit 5
UNION ALL 
SELECT * FROM table_2 limit 5



need to encompass SELECT ... UNION ALL SELECT ... 'within a select with limit 10 something like:

select * from 
(Select * FROM tbl_1) T1, 
UNION ALL 
(Select * FROM tbl_2) T2, 
limit 10

this example does not work, is just to exemplify how I need to get the query
is a real case ... can someone lend a hand?
thank you

Was it helpful?

Solution

When using unions then it is best to select the columns individually to ensure they match between the queries. It is also worthwhile setting column aliases on the first query so that you can refer to them uniquely in the other parts of query.

I have amended this answer to demonstrate the use of 'sort keys' that are selected for each individual query then applied by the outer query that controls which columns are displayed. And what order they are displayed.

I have also provided a SQLFiddle... that you can use to 'play' with it.

tested example:

SELECT report.title 
FROM 
(SELECT title AS title,
       'Q01'  AS query_identifier, 
       id     AS sort_key_01,        
        0     AS sort_key_02 
FROM parents
UNION 
SELECT child_text,
       'Q02',  
        parent_id, 
        id  FROM children
) report
ORDER BY 
         report.query_identifier, 
         report.sort_key_01, 
         report.sort_key_02

result:

first parent title
second parent title
third parent title
first parent first child
first parent second child
second parent first child
second parent second child
third parent first child
third parent second child
third parent third child

OTHER TIPS

It should be like below:

(SELECT * FROM table_1)
UNION ALL 
(SELECT * FROM table_2)
LIMIT 10 

To use an ORDER BY or LIMIT clause to sort or limit the entire UNION result, parenthesize the individual SELECT statements and place the ORDER BY or LIMIT after the last one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top