dsfdfdfd6576578 2016-08-14 18:31
浏览 90

MySQL加入和最新的批次信息

I have four tables. The first describing a mix of items. The second is a linking table between the mix, and the items. The third is the item table, and the fourth holds lot information - lot number, and when that lot starts being used.

mix

mixID | mixName
----------------
1     | Foxtrot
2     | Romeo

mixLink

mixID | itemID
----------------
1     | 1
1     | 2
1     | 3

item

itemID| itemName
----------------
1     | square
2     | triangle
3     | hexagon

itemLots

itemID| lotNo | startDate
-------------------------
1     | 22/5/3| 22/07/16
2     | 03/5  | 25/07/16
2     | 04/19 | 12/08/16
3     | 15/0  | 05/08/16

Now, I need to be able to fetch the information from the database, which details all the items from a mix, as well as the most recently used lot number, something like this:

itemName | lotNo
----------------
square   | 22/5/3
triangle | 04/19
hexagon  | 15/0

I've tried a dozen different mixes of joins, group by's, maxes, subqueries, and havings; all to no avail. Any help would be much appreciated, I've been pulling my hair out for hours, and I feel like my fingernails are just scraping at the solution!

  • 写回答

1条回答 默认 最新

  • doudou20080720 2016-08-15 00:52
    关注

    This will give you the result you're after and will perform pretty well if you have your indexes done properly. I'm not sure how you're meaning to reference mix as it's not apparent in your sample output but I've included it in the WHERE clause so hopefully you can understand where you would use it.

    SELECT i.itemName
    , (SELECT il.lotNo FROM itemLots il 
    WHERE il.itemID=i.itemID
    ORDER BY il.startDate desc
    LIMIT 1) as lotNo
    FROM item i 
    JOIN mixLink ml ON ml.itemID=i.itemID
    JOIN mix m ON m.mixID=ml.mixID
    WHERE m.mixName="Foxtrot";
    
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法