need help/guide for sql select query, I have 2 table stock and stock_history, in stock will have initial values for stock
and before update the stock table,stock_history will be inserted 1st from stock table, my case is need to get status of stock based on selection date,
this is to track open stock balance and close stock balance, close stock balance is easy where just need to fetch data from table stock
for particular timestamp, but the critical part is when to fetch data for open stock balance where need trace the status for specific timestamp,
this only can be done by refering the history table, so i need the sql where need to select data from both stock and stock_history
status table
id desc
-- ----
01 consignment
02 customer
03 bank
04 safekeep
05 exit
stock
-----
ref_no serial_no status timeStamp
1 001 04 2012-03-01 09:03:00
stock_history
-------------
ref_no serial_no status timeStamp
1 001 01 2012-03-01 09:00:00
1 001 03 2012-03-01 09:01:00
1 001 02 2012-03-01 09:02:00
so, when choose for date
01/03/12 time 9:01 = 1 001 03 2012-03-01 09:01:00
01/03/12 time 9:01 = 1 001 03 2012-03-01 09:01:00
please help, thanks in advance
You can use the UNION operator to select from multiple tables:
That said, I’d suggest restructuring your schema. Why have a separate “stock” and “stock_history” table? You really only need one “stock” table to store both — the “current” stock is just the one with the highest status. Or you could even be explicit and maintain an “is_current” flag row.
Update: Changed
UNIONtoUNION ALL. TheALLmeans just combine the rows for both tables, no extra processing. Leaving it off will attempt to remove any duplicate rows first, which could be less efficient (and makes no difference in the results here since duplicates are not possible with your schema). Hat tip to @SmartestVEGA.