user455982
user455982

Reputation:

Fetch the top 5 records from 2 tables each using single query

I want to fetch the top 10 records from 2 tables which have id as reference id using single query.

For example, I have student and Student_details tables.

Now I want to fetch top 5 records of student table and top 5 records of Student_details table.

Upvotes: 2

Views: 767

Answers (5)

Thariama
Thariama

Reputation: 50832

This is not possible! You could create a temporary table and somehow try to match the fields of one table to match the field of the other if they both have almost the same number of fields - only then you could use a single query to get the top 5 results of both tables using one query. But even then this would lead to more than a single query (because you had to create the temp table first).

The best you can do is to use two queries:

SELECT * FROM student ORDER BY student.id LIMIT 5;
SELECT * FROM student_details ORDER BY student_details.id LIMIT 5;

Upvotes: 0

acme
acme

Reputation: 14856

Do you want to have the results from both tables combined in 1 result set?

If so, then use

SELECT student.*, student_details.*
FROM student, student_details
WHERE student.id = student_details.student_id
ORDER BY id ASC LIMIT 5;

Upvotes: 2

Some Noob Student
Some Noob Student

Reputation: 14594

SELECT * FROM table WHERE ... ORDER BY ... DESC/ASC LIMIT 5;

Do it twice.

Upvotes: 0

BeemerGuy
BeemerGuy

Reputation: 8269

SELECT * FROM STUDENTS ORDER BY ID LIMIT 5

Upvotes: 0

Svisstack
Svisstack

Reputation: 16636

SELECT * FROM student ORDER BY id ASC LIMIT 5;
SELECT * FROM student_details ORDER BY id ASC LIMIT 5;

Upvotes: 1

Related Questions