[英]When selecting a record from a joined table get the most recent record from the B (joined) table for each A table record if possible
[英]SQL indexing on lines from joined table on each record from the original
我有两张桌子。
订单(o)
id | buyer
1 | Joe
2 | Ann
3 | Sue
和Order_Items(oi)
id | master_record_id | stock number | qty
1 | 1 | 1234 | 1
2 | 1 | 7890 | 1
3 | 1 | 4987 | 1
4 | 2 | 1234 | 1
5 | 2 | 7890 | 1
6 | 2 | 4987 | 1
7 | 3 | 1234 | 1
8 | 3 | 7890 | 1
9 | 3 | 4987 | 1
表oi取决于oi.master_record_id的命令。 表oi中的每条记录(id)都是唯一的(没有存储该订单中的哪个项目),因此对于该示例,我有3条订单,每行3行,在表oi中,我有9条ID为1到1的记录9。
我的问题是我应该使用哪种查询来导出订单(每个订购商品一行),其中每个oi都有一个基于其连接到的订单的索引:
输出示例:
o.id | o.buyer | Required: Item on Order | oi.stock_number
1 | Joe | 1 | 1234
1 | Joe | 2 | 7890
1 | Joe | 3 | 4987
2 | Ann | 1 | 1234
2 | Ann | 2 | 7890
2 | Ann | 3 | 4987
3 | Sue | 1 | 1234
3 | Sue | 2 | 7890
3 | Sue | 3 | 4987
非常感谢,
丹妮
在MySQL中,您可以使用“用户变量”生成行号。 为您的oi记录生成行号,并与Orders表一起获取结果。 这是一篇很好的博客文章 ,介绍如何在MySQL中实现行编号。
SELECT id,buyer,Item_on_Order,stock_number
FROM
(SELECT O.`id` as id,
O.`buyer` as buyer,
(@row_num := IF(@category=O.`id`,@row_num+1,1)) as Item_on_Order,
OI.`stock_number` as stock_number,
@category := O.`id` AS Temp
FROM
Orders O
INNER JOIN Order_Items OI ON O.`id` = OI.`master_record_id`)T
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.