0

I have 2 tables, stock and store

stock:

|-----------------|                      
|  Id | store_id  |
|-----|-----------|                        
|   1 |           |                                 
|-----|-----------|
|   2 |           |  
|-----|-----------|                                           
|   3 |           |  
|-----|-----------|                              
|   4 |           |                                                             
|-----|-----------|

store:

|-----------------|
|  Id | name      |
|-----|-----------|
|   21|   aaaa    |  
|-----|-----------|
|   12|    bbbb   |  
|-----|-----------|

I need to loop over store table and and put its id in stock table's store_id column, the result should be:

|-----------------|                      
|  Id | store_id  |
|-----|-----------|                        
|   1 |    21     |                                 
|-----|-----------|
|   2 |    12     |  
|-----|-----------|                                           
|   3 |    21     |  
|-----|-----------|                              
|   4 |    12     |                                                             
|-----|-----------|

I have tried some example like Postgresql Update inside For Loop

But didn't get a solution... plz help

4
  • 1
    You don't want to use a loop. A loop is almost always the wrong solution in SQL. How are you determining which store_id goes with each id in stock? Commented Nov 13, 2019 at 18:23
  • it is like 21 will go first and then 12 will go and so on. Commented Nov 13, 2019 at 18:30
  • You need to add all products to all stores? Cross Join. Commented Nov 13, 2019 at 18:45
  • @AbhishekKumar When saying "first", do you mean ordered by stock id? Or something else? By "and so on", you mean alternatingly? Commented Nov 13, 2019 at 20:25

1 Answer 1

0

I'm a bit skeptical that this is what you actually want, but from what you describe, it seems like this is the answer:

UPDATE STOCK SET store_id = (CASE WHEN id%2=1 THEN 21 ELSE 12 END);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.