douhezhan5348 2015-07-30 22:01
浏览 69
已采纳

Mysql,一对多的关系,需要最新的

It's a long time since I've worked with MySQL and I'm learning fast, with a lot of help from stackoverflow along the way. This one has me stumped though. I'm certain I've done something similar in the past but despite trying a few things I haven't achieved it yet. I suspect last time I had to utilise PHP code to ignore duplicate rows but I'm not so sure.

I am working with two tables. Table 1 has a unique record for every year, and a reference to a dept. Table 2 stores the head of each dept, and the year they were appointed.

Table 1          Table 2
Year | Dept      Dept | Head       | Since Year
1982 | 1         1    | Hutchinson | 1979
1983 | 2         1    | Holroyd    | 1983
1984 | 2         1    | Farrey     | 1987
1985 | 2         2    | Mainwaring | 1983
1986 | 1         2    | Blanche    | 1985
1987 | 2         3    | Sunt       | 1986
1988 | 3

What I need is a query that returns the person in charge of the referenced dept at the year in question. Like this:

1982 | 1 | Hutchinson
1983 | 2 | Mainwaring
1984 | 2 | Mainwaring
1985 | 2 | Blanche
1986 | 1 | Holroyd
1987 | 2 | Blanche
1988 | 3 | Sunt

MySQL has moved on a fair bit since I last used it. Sub-queries weren't a thing back then and I'm thinking they might help here? Any advice appreciated.

  • 写回答

2条回答 默认 最新

  • dougu1990 2015-07-30 22:35
    关注

    You don't have to use subquery.

    Just select valid Heads twice and then discard those where there exists Head appointed later.

    SELECT t1.*,t2.Head 
    FROM Table1 t1
    JOIN Table2 t2 ON t1.Dept = t2.Dept AND t1.Year >= t2.`Since Year`
    LEFT JOIN Table2 t22 ON t2.Dept = t22.Dept AND t1.Year >= t22.`Since Year` AND t2.`Since Year` < t22.`Since Year` 
    WHERE t22.Head IS NULL
    

    t2.`Since Year` < t22.`Since Year` find Heads appointed later than current Head

    WHERE t22.Head IS NULL select only Heads without successor

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图