MySQL – Join Two Tables and Limit by First Input

MySQL

i am only starting to play with MySQL and i seem to have been stumped by one problem.

I have one table containing a number of fields including a primary id field. I have a second table containing multiple rows with the value of user_id corresponding to the first table.

Or, this

Table 1:
Id name
1 foo
2 bar
3 baz
4 qux

Table 2:
id uid
1 1
2 2
3 2
4 2
5 3

I need to make a query with a limit i.e say LIMIT 3
Then the first 3 rows of table 1 should be selected, and all rows from table 2 having uid between 1 and 3 (The ids of the first 3 rows) should be returned.

Best Answer

You can use something like this:

select * from 
(select * from table1 limit 3) t1
join table2 t2 on t2.uid = t1.id

You can check it: http://sqlfiddle.com/#!2/1a534/7