从表中选择具有来自不同表的多个行值的单行

时间:2014-03-27 19:14:18

标签: sql

我有2个MySQL表,我想为TableA中的每个记录选择1行,但每个记录最多可以有2个"付款人"来自TableB的记录,所以我希望表B中的每个值都是一行。

以下是我所拥有的表格的一个小例子:

TableA 
RecordID |      Name |         Date |
       1 | 'Record1' | '2014-01-01' |
       2 | 'Record2' | '2014-01-02' |

TableB 
RecordID | AmountPaid | PayerCount | PayerCode |
       1 |     $10.99 |          1 |      1234 |
       1 |     $15.99 |          2 |      9876 | 
       2 |     $27.99 |          1 |      1234 | 
       2 |     $61.99 |          2 |      9876 |

TableB.PayerCount:1 =第一个付款人,2 =第二个付款人。

这是我想从这些表格中获取的信息:

ID |      Name |         Date | FirstPayerCode | FirstPayerAmount | SecondPayerCode | SecondPayerAmount |
 1 | 'Record1' | '2014-01-01' |           1234 |           $10.99 |            9876 |            $15.99 |
 2 | 'Record2' | '2014-01-02' |           1234 |           $27.99 |            9876 |            $61.99 |

我似乎无法找到能给我这些结果的任何东西。

非常感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:2)

SELECT      tableA.id, tableA.name, tableA.date, 
            FirstPlayerCode, FirstPlayerAmount, 
            SecondPlayerCode, SecondPlayerAmount 
FROM        tableA
LEFT JOIN   (SELECT PayerCode AS FirstPlayerCode, AmountPaid AS FirstPlayerAmount 
             FROM   tableB
             WHERE  PlayerCount = 1) p1 ON p1.RecordID = tableA.RecordID 
LEFT JOIN   (SELECT PayerCode AS SecondPlayerCode, AmountPaid AS SecondPlayerAmount 
             FROM   tableB
             WHERE  PlayerCount = 2) p2 ON p2.RecordID = tableA.RecordID