简体   繁体   中英

SQL indexing on lines from joined table on each record from the original

I have two tables.

Orders (o)

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

And 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. 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.

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:

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. Generate row numbers for your oi records and join with your Orders table to get your results. Here is a good blog post on how to achieve row numbering in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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