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.
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;
SELECT * FROM student ORDER BY id ASC LIMIT 5;
SELECT * FROM student_details ORDER BY id ASC LIMIT 5;
SELECT * FROM STUDENTS ORDER BY ID LIMIT 5
SELECT * FROM table WHERE ... ORDER BY ... DESC/ASC LIMIT 5;
Do it twice.
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;
精彩评论