我有两个表,每个表包含超过一百万行。这两个表看起来像这样; 表1
student_id student_name
001 mark
002 moses
003 mike
004 john
005 jeff
006 joe
和 表2
student_id height weight
001 170 80
002 130 88
003 190 90
004 150 75
005 200 85
006 180 78
如果他们的身高在150厘米到200厘米之间,那么返回前4个体重的学生应该是什么意思;像这样的东西
student_id student_name weight
003 mike 90
005 jeff 85
001 mark 80
006 joe 78
我尝试过类似的东西,但它不起作用;
SELECT a.student_id AS `Student ID`, a.student_name AS `Student Name`, b.weight
FROM table1 AS a
RIGHT JOIN
(
SELECT student_id
FROM table2
WHERE height BETWEEN 150 AND 200 ORDER BY weight DESC LIMIT 4
) AS b
ON b.student_id
WHERE a.student_id IN b.student_id
任何达到所需结果的方法都受到高度赞赏。 提前谢谢!
答案 0 :(得分:2)
我使用的是SQL Server,但我认为这应该有用......
SELECT table2.student_id as 'Student ID',
table1.student_name AS 'Student Name',
table2.weight
FROM table2
INNER JOIN table1 ON table1.student_id = table2.student_id
WHERE table2.height BETWEEN 150 AND 200
ORDER BY table2.weight DESC
LIMIT 4
答案 1 :(得分:0)
我会使用LEFT JOIN
IE
SELECT a.student_id, a.student_name, b.weight
FROM table1 a
LEFT JOIN table2 b
ON a.student_id = b.student_id
WHERE b.hieght
BETWEEN 150
AND 200
ORDER BY b.weight DESC LIMIT 4;