简体   繁体   English

从原始表的每个记录上的联接表的行上的SQL索引

[英]SQL indexing on lines from joined table on each record from the original

I have two tables. 我有两张桌子。

Orders (o) 订单(o)

id | buyer  
1  | Joe  
2  | Ann  
3  | Sue  

And Order_Items (oi) 和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  

Table oi is dependable on orders by oi.master_record_id. 表oi取决于oi.master_record_id的命令。 Every record (id) in table oi is a unique one (there is no storing of which item this is on an order) so for the example I have 3 orders each with 3 lines and in table oi I have 9 records with ids 1 to 9. 表oi中的每条记录(id)都是唯一的(没有存储该订单中的哪个项目),因此对于该示例,我有3条订单,每行3行,在表oi中,我有9条ID为1到1的记录9。

My question is what query should I use to be able to export the orders (a line for each ordered item) where each oi has an index based on the order it is connected to: 我的问题是我应该使用哪种查询来导出订单(每个订购商品一行),其中每个oi都有一个基于其连接到的订单的索引:

Example output: 输出示例:

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

Many Thanks, 非常感谢,

Dani 丹妮

In MySQL, you can use "user variables" to generate row numbers. 在MySQL中,您可以使用“用户变量”生成行号。 Generate row numbers for your oi records and join with your Orders table to get your results. 为您的oi记录生成行号,并与Orders表一起获取结果。 Here is a good blog post on how to achieve row numbering in MySQL. 这是一篇很好的博客文章 ,介绍如何在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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM