2014-03-27 59 views
0

我有2个MySQL表,我想为TableA中的每个记录选择1行,但每个记录最多可以有2个来自TableB的“Payer”记录,所以我希望每个表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

你写了什么SQL? – broinjc

+0

现在,我只是得到2行的每个记录与“SELECT * FROM TableA JOIN TableB USING(RecordID)”。但是我为每个记录标识需要一行,但不能想到(或找到)我需要的语法。 –

回答

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 
+0

美丽,这正是我需要的。我不知道你可以加入选择声明。谢谢您的帮助! –

相关问题