如何从单个数据库中获取多个表中的数据

时间:2012-08-12 17:14:04

标签: sql database foreign-keys

 i have three tables file, expense and payment. I want fetch data from 3 table based on foreign key.

我有以下三个表

文件表

FileId
FileNo

付款表

  Id
  Amount
  FK_FileID

费用表

  Id
  Amount
  FK_FileID

我想输出

FileNo      Amount  IsPayment
10001         220         True
10001         120         False
10001         150         True

IsPayment是逻辑字段如果金额来自付款表,则IsPayment应该为真,如果是来自费用表则应该为假。

1 个答案:

答案 0 :(得分:0)

我想这个查询应该可以解决问题:

SELECT ft.FileNo, pt.Amount, 'True' IsPayment
FROM FileTable ft
JOIN PaymentTable pt ON pt.FK_FileID = ft.FileId
UNION ALL
SELECT ft.FileNo, et.Amount, 'False' IsPayment
FROM FileTable ft
JOIN ExpenseTable et ON et.FK_FileID = ft.FileId