I’m trying to implement a very basic banking system. the goal is to have different types of transactions ( deposit, withdraw, transfer ) inside a table and refer to them as IDs inside transaction tables.
CREATE TABLE transaction_types ( id INTEGER AUTO_INCREMENT PRIMARY KEY, name VARCHAR UNIQUE NOT NULL ) CREATE TABLE transactions ( id INTEGER AUTO_INCREMENT PRIMARY KEY, type_id INTEGER NOT NULL, amount FLOAT NOT NULL )
What I’m trying to accomplish is:
- When inserting into
transactions
table no record can have an invalidtype_id
(type_id
should exist intransaction_types
table ) - First of all get
type_id
fromtransaction_types
table and then insert insidetransactions
table, with one query ( if it’s possible, I’m fairly new )
I’m using Node.js/Typescript and PostgreSQL, any help is appreciated a lot.
Advertisement
Answer
For (1): modify Transactions table definition by adding REFERENCES transaction_types(id)
to the end of the type_id column definition prior to the comma.
For (2), assuming you know the name of the transaction_type, you can accomplish this by:
INSERT INTO transactions(type_id, amount) VALUES ((SELECT id from transaction_types WHERE name = 'Withdrawal'), 999.99)
By the way, my PostgreSQL requires SERIAL
instead of INTEGER AUTOINCREMENT