我有一个具有以下表结构的MySQL数据库:
TransactionType :Transaction_Amount,Transaction_ID,Transaction_Form
交易:Transaction_ID,时间戳
购买:Transaction_ID,Item_ID
商品:Item_ID,Client_ID
这实际上是一个两部分的问题(如果我将这些问题作为两个单独的问题发布,请告诉我)
1)TransactionType.Transaction_Form本质上是一个列,用于确定交易是现金还是信贷。有没有办法将这两个查询结合起来?
SELECT SUM(Transaction_Amount)
FROM Transaction_Type WHERE Transaction_Form = 'cash'
和
SELECT SUM(Transaction_Amount)
FROM Transaction_Type WHERE Transaction_Form = 'credit'
2)我需要根据正在使用的client_id选择这两个transaction_amount。
我能想到的唯一方法就是:
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
这显然不是那么漂亮......
我是否需要在事务中添加client_id列?这会多余吗?
-Thanks
答案 0 :(得分:2)
1:
SELECT transaction_form, SUM(transaction_amount)
FROM transaction_type
GROUP BY transaction_form
答案 1 :(得分:2)
使用:
SELECT SUM(tt.transaction_amount)
FROM TRANSACTION_TYPE tt
WHERE tt.transaction_form IN ('cash', 'credit')
...如果你想要两者的transaction_amount组合。如果您希望它们分开,请使用:
SELECT tt.transaction_form,
SUM(tt.transaction_amount)
FROM TRANSACTION_TYPE tt
WHERE tt.transaction_form IN ('cash', 'credit')
GROUP BY tt.transaction_form
使用:
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 = ?