Now that we've explored the concept and importance of joins in relational databases, it's time to put these principles into practice. With the context of a finance application, let's implement joins in our database system.
When implementing joins, we look for related data from two separate tables. Let's consider two tables in the finance application database: Stocks
and Transactions
. The Stocks
table contains an ID, stock symbol, and company name, while the Transactions
table includes the transaction ID, stock ID (which matches the ID in the Stocks
table), transaction type (buy or sell), number of shares, and price.
Implementing a JOIN operation in our database system could help answer questions like, 'What are all the transactions involving a specific stock?'
We can represent a simple INNER JOIN with Python as follows:
xxxxxxxxxx
if __name__ == "__main__":
# Defining the table data
Stocks = [(1, 'AAPL', 'Apple Inc.'), (2, 'GOOG', 'Alphabet Inc.'), (3, 'TSLA', 'Tesla Inc.')]
Transactions = [(101, 1, 'buy', 100, 150.0), (102, 3, 'sell', 50, 800.0), (103, 2, 'buy', 75, 1200.0), (104, 1, 'sell', 120, 140.0)]
# Implementing a simple inner join
transactions_with_stocks = [(t[0], s[1], t[2], t[3], t[4]) for s in Stocks for t in Transactions if s[0] == t[1]]
print('Transactions with Stocks:', transactions_with_stocks)