在不更改表结构的情况下,如何实现以下目标:
我有三个表:student
,book_price
和book_data
。
我想显示每个学生的max(price)
的详细信息。
学生桌
student_id student_name
1 Sarah
2 John
3 Peter
book_price表
price_id student_id book_id price
105 1 464 15.07
106 1 557 26.80
205 2 329 16.48
207 2 331 11.05
217 3 202 19.95
book_data表
book_id book_name book_image
464 Goodnight Moon site_url_1
557 The Snowy Day site_url_4
329 Harry Potter site_url_2
331 Green Egg site_url_5
202 The Hobbit site_url_3
结果应为:
student_id student_name price book_name book_image
1 Sarah 26.80 The Snowy Day site_url_4
2 Peter 19.95 The Hobbit site_url_3
2 John 16.48 Harry Potter site_url_2
最佳答案
这是您的问题的解决方案:
SELECT st.student_id,
st.student_name,
bp.price,
bd.Book_name,
bd.book_image
FROM Student st
INNER JOIN book_price as bp ON st.student_id = bp.student_id
INNER JOIN book_data as bd ON bp.book_id = bd.book_id
INNER JOIN (
SELECT Student_id, MAX(price) AS price
FROM book_price
GROUP BY Student_id) AS t ON bp.student_id = t.student_id
AND bp.price = t.price
ORDER BY bp.price DESC
输出:
student_id student_name price Book_name book_image
1 Sarah 26.8 The Snowy Day site_url_4
3 Peter 19.95 The Hobbit site_url_3
2 John 16.48 Harry Potter site_url_2
链接到演示:
http://sqlfiddle.com/#!9/7d4d0d/10
关于mysql - 用MAX函数联接三个表,表结构有点复杂,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50054766/