当两个表(没有关系)与一个

时间:2015-08-27 15:52:04

标签: sql

我试图通过谷歌搜索找到解决方案,但由于我的要求而感到困惑。我想查询已经贷款的借款人总数。我用两个表(即表1和表2)完成了它,但是无法用三个表获得所需的结果。

以下是表格I&#t; ve:

Table 1 [Connected with Table2 and Table3]

+--------------------------------------------------+
| Id | Name   |  AmountDue | GivenOn    | PayMode  |
+--------------------------------------------------+
| 1  | John   |  5000      | 01/01/2015 | Weekly   |
| 2  | Shail  |  100       | 01/01/2015 | Custom   |
| 3  | James  |  500       | 01/01/2015 | Monthly  |
+--------------------------------------------------+

      Table 2 [For Weekly & Monthly Loan]

+-------------------------------------------------+
| Id | InstNo | InstAmt | DueON      | PaidON     |
+-------------------------------------------------+
| 1  | 1      |   2500  | 08/01/2015 | 08/01/2015 |
| 1  | 2      |   2500  | 15/01/2015 | 01/01/1900 | 
| 3  | 1      |    250  | 01/02/2015 | 01/01/1900 |
| 3  | 2      |    250  | 01/03/2015 | 01/01/1900 |
+-------------------------------------------------+

        Table 3 [For Custom]

+--------------------------------------------------------------------------+
| Id | Principle | Interest | TotalDue | DueON      | PaidAmt |   PaidON   |
+--------------------------------------------------------------------------+
| 2  | 1000      | 20       | 1020     | 01/02/2015 |       0 | 01/01/1900 |
+--------------------------------------------------------------------------+

如果我搜索其PaidON日期= 01/01/1900

的借款人,我希望得到以下结果
+-----------------------+
| Id | Name   | PayMode |
+-----------------------+
| 1  | John   | Weekly  |
| 2  | Shail  | Custom  |
| 3  | James  | Monthly |
+-----------------------+ 

2 个答案:

答案 0 :(得分:0)

您可以使用ExistsOr来确定ID是在表2还是表3中

SELECT
    Id,
    Name,
    PayMode
FROM
    Table1 t1
WHERE 
    EXISTS (SELECT * FROM Table2 t2 WHERE t2.Id = t1.Id AND t2.PaidOn = '01/01/1900')
    OR EXISTS (SELECT * FROM Table3 t3 WHERE t3.Id = t1.Id AND t3.PaidOn = '01/01/1900')

答案 1 :(得分:0)

试试这个

SELECT DISTINCT t1.Id,t1.Name,t1.Paymode
FROM table1 t1 LEFT JOIN table2 t2 ON t1.id = t2.id
LEFT JOIN  table3 t3 ON t1.id = t3.id
WHERE COALESCE(t2.PaidON,t3.PaidON)= '01/01/1900'