patternsqlMinor
Mysql join two tables and limit by first input?
Viewed 0 times
tableslimitjoininputmysqltwofirstand
Problem
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
Or, this
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.
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 3I 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.
Solution
You can use something like this:
You can check it: http://sqlfiddle.com/#!2/1a534/7
select * from
(select * from table1 limit 3) t1
join table2 t2 on t2.uid = t1.idYou can check it: http://sqlfiddle.com/#!2/1a534/7
Code Snippets
select * from
(select * from table1 limit 3) t1
join table2 t2 on t2.uid = t1.idContext
StackExchange Database Administrators Q#63517, answer score: 5
Revisions (0)
No revisions yet.