dougu1952 2014-04-19 06:29
浏览 55
已采纳

内部联接限制左表结果限制为1

I have two tables. One is students and other one is results. Now student id in studetnt's table is unique but one student can have multiple rows in results table.

I want to join both tables and produce exactly one resulting row for every student. This row will contain student's info (name,image etc) and most recent student result.

I have applied inner join to achieve this but I am getting separate row for each entry in results table. If I apply limit 1 it gives me result with only one student's data and not every student's.

Here is the query:

SELECT students.id,
       students.roll_num,
       students.first_name,
       students.middle_name,
       students.last_name,
       students.course,
       students.photo_url,
       results.parano,
       results.grade
FROM students
RIGHT JOIN results ON results.std_id=students.id

And here is what I get in results:

enter image description here

  • 写回答

3条回答 默认 最新

  • douba2011 2014-04-19 07:19
    关注

    recent student result is a key. This will complicate query...

    SELECT
        st.id,
        st.roll_num,
        st.first_name,
        st.middle_name,
        st.last_name,
        st.course,
        st.photo_url,
        rs1.parano,
        rs2.grade 
    FROM students st, results rs1, results rs2 
    WHERE rs1.std_id=st.id AND rs2.std_id=st.id 
    GROUP BY st.id
    HAVING 
            count(rs1.parano) = 
            (SELECT count(rs.parano) 
            FROM results rs 
            WHERE rs.std_id=st.id 
            ORDER BY count(rs.parano) 
            LIMIT 1)
    AND     count(rs2.grade) = (
            SELECT count(rs.grade) 
            FROM results rs 
            WHERE rs.std_id=st.id 
            ORDER BY count(rs.grade) 
            LIMIT 1)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集