Derek Adair
Derek Adair

Reputation: 21925

MySQL table structure

I have a MySQL database with the following table structure:

TransactionType: Transaction_Amount, Transaction_ID, Transaction_Form
Transaction: Transaction_ID, Timestamp
Purchase: Transaction_ID, Item_ID
Items: Item_ID, Client_ID

This is really a two part question (please let me know if i should post these as two separate questions)

1) TransactionType.Transaction_Form is essentially a column to determine if a transaction was cash or credit. Is there a way to combine these two queries?

SELECT SUM(Transaction_Amount) 
FROM Transaction_Type WHERE Transaction_Form = 'cash'

and

SELECT SUM(Transaction_Amount) 
FROM Transaction_Type WHERE Transaction_Form = 'credit'

2)I have the need to select these two transaction_amount's based upon the client_id being used.

The only way I can think of to do this is something like:

SELECT Transaction_Amount FROM Transaction_Type 
JOIN Transaction ON Transaction_Type.Transaction_ID=Transaction.Transaction_ID
JOIN Purchase ON Transaction.Transaction_ID = Purchase.Transaction_ID
JOIN Items ON Purchase.Item_ID = Item.Item_ID
WHERE Items.Client_ID = $clientId

Which is obviously not all that pretty...

Do I need to add a client_id column into transaction? Would that be redundant?

-thanks

Upvotes: 0

Views: 184

Answers (2)

OMG Ponies
OMG Ponies

Reputation: 332571

Part 1:

Use:

SELECT SUM(tt.transaction_amount)
  FROM TRANSACTION_TYPE tt
 WHERE tt.transaction_form IN ('cash', 'credit')

...if you want the transaction_amount for both combined. If you want them separate, use:

  SELECT tt.transaction_form,
         SUM(tt.transaction_amount)
    FROM TRANSACTION_TYPE tt
   WHERE tt.transaction_form IN ('cash', 'credit')
GROUP BY tt.transaction_form

Part 2:

Use:

SELECT tt.transaction_amount
  FROM TRANSACTION_TYPE tt
  JOIN PURCHASE p ON p.transaction_id = tt.transaction_id
  JOIN ITEMS i ON i.item_id = p.item_id
 WHERE i.client_id = ?

Upvotes: 2

rosscj2533
rosscj2533

Reputation: 9323

1:

SELECT transaction_form, SUM(transaction_amount) 
FROM transaction_type 
GROUP BY transaction_form

Upvotes: 2

Related Questions