用MAX函数连接三个表,表结构有点复杂

时间:2018-04-27 03:26:48

标签: mysql sql

如果不更改表格结构,我该如何实现以下目标:

我有三张牌桌:studentbook_pricebook_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 table

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

2 个答案:

答案 0 :(得分:3)

以下是您的问题的解决方案:

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

答案 1 :(得分:1)

SQL Fiddle Link

select student_id,student_name,price,book_id,book_image from (
  select *,
      CASE student_id 
          WHEN @curId THEN
            @curRow := @curRow + 1 
          ELSE @curRow :=1
      END AS rank,
      @curId := student_id AS student_id2
  from (
    select stu.student_id ,
        stu.student_name,
        max(bp.price) price,
        bd.book_id,
        bd.book_image
    from book_price bp
    left join student stu on stu.student_id = bp.student_id
    left join book_data bd on bd.book_id = bp.book_id 
    group by stu.student_id,stu.student_name
        ,bd.book_id,bd.book_image
    ORDER BY student_id,price DESC
  ) T
  JOIN (SELECT @curRow := 0, @curId := 0) r
)T2
where rank = 1

相关问题