sql - Operation on each row from select query -


How to execute additional queries (updates) on each line from SELECT? I'll have to get the amount from each row by choosing and send it to the user's balance table.

Example:

  Status 0 - Open position 1 - Processed status 2 - Off  

My selection statement:

(Prefix = 1 or condition = 1) and type = 0) from (preceded by), select id, user_id, sell_amount, sell_currency_id (id, select user_id, sell_amount, sell_currency_id, sum (sell_amount) T where 0 & lt; = Cumsell and 7 & gt; From cumsell as buy_amount / sell_amount asc, date_add by ASC) Cumsell - sell_amount;

Select results from the market table

  ID; User_id; Zodiac; Position 4; 1; 1.00000000; 0 6; 2; 2.60000000; 0 5; 3; 2.00000000; 0 7; 4; 4.00000000; 0  

We get 7 zodiac and send it to user balance table.

  id; User_id; Zodiac; Position 4; 1; 0.00000000; 2 - 1 taken, zodiac 1, position 2 6; 2; 0.00000000; 2 - 2.6 taken, yoga = 3.6, changed from position 2; 3; 0.00000000; 2- Taken 2, zodiac 5.6, changing position from 2 to 7; 4; 2.60000000; 1 - 1.4, Right 7.0, the position was changed to 1 (because 2.6 was closed from there)  

The user's remaining table

  User_id; Remaining 5; 7 - 7 Added from previous operation  

Postgrass version 9.3

The general principle for using UPDATE ... FROM on a subcategory is to convert your example into a very useful create table and SELECT statement , So I have created a quick dummy dataset:

  create a table equilibrium (user_id integer, remaining numeric); Invest in Balance (user_id, balance) Price (1,0), (2, 2.1), (3, 99); Create table transactions (user_id integer, numeric, applied boolean default 'F'); Include in transaction (user_id, amount) value (1, 22), (1, 10), (2, -10), (4, 1000000);  

If you want to apply the transaction for balance, then you will do something like this:

  BEGIN; Lock table balance in exclusive MODE; Pond transactions in exclusive mode; Balance from updated balance = Balance + T.M. (Select T2 User_ID, Amount (T.A.M.M.) T. Group by T2 Group T.User_ID) T is the balance where the balance. User_id = t User ID; Update the transaction SET applicable = Balance balance WHERE transaction.USCE_ID = B. User ID;   

The LOCK statement is important for correcting the presence of concurrent inserts / updates.

The second UPDATE marks the transaction that applies; You do not need anything in your design.


Comments