0

我有两张表,一张用于客户信用(付款),它看起来像这样:

id     client     date              amount
1       ana       2012-01-01        5000  
2       ana       2012 02-01        10000
3       ana       2012-03-01        5000

ETC ..

和另一个看起来像这样的借记(取款)表:

id    client      date             amount 
1       ana       2012-01-15        5000
2       ana       2012 02-15        8000
3       ana       2012-03-15        9000

ETC ...

我想生成一个查询,按日期对每个客户的所有交易进行排序,将 2 个日期列合并为一个,然后按日期排序,它应该如下所示:

date           payment     withdrawal 
2012-01-01     5000           ----
2012-01-15     -----          5000
2012-02-01     10000          ----  
2012-02-15     -----          8000
2012-03-01      5000          ----
2012-03-15     -----          9000

这是我尝试过的,但我知道它是错误的,并且它给出了重复的记录:

SELECT payments.amount, payments.date withdrawals.amount, withdrawals.date
FROM payments,withdrawals 
WHERE payments.client = withdrawals.client
ORDER BY date

我尝试了 LEFT JOIN 但它给出了相同的结果:

 SELECT payments.amount, payments.date, withdrawals.amount, withdrawals.date
 FROM payments 
 LEFT JOIN withdrawals 
 ON payments.client= withdrawals.client
 ORDER BY date

请帮忙,谢谢

4

2 回答 2

2

您需要执行两个简单的 SELECT 查询,分别在每个表上执行一个,然后使用 UNION 关键字组合结果,如下所示:

SELECT date, amount AS payment, NULL AS withdrawal FROM payments WHERE client = 'ana'
UNION ALL
SELECT date, NULL AS payment, amount AS withdrawal FROM withdrawals WHERE client = 'ana'
ORDER BY date

您不想进行任何类型的连接,因为每一行的数据只从一个表中提取,而不是从另一个表中提取。

于 2013-04-15T08:25:27.983 回答
-1

你正在寻找的是一个完整的外部连接:

SELECT payments.amount, payments.date, withdrawals.amount, withdrawals.date
FROM payments FULL OUTER JOIN withdrawals
  ON payments.client= withdrawals.client
Order by date

或者使用 UNION(根据 MySQL 的需要):

SELECT payments.amount, payments.date, withdrawals.amount, withdrawals.date
FROM payments LEFT OUTER JOIN withdrawals
  ON payments.client= withdrawals.client
Order by date
UNION
SELECT payments.amount, payments.date, withdrawals.amount, withdrawals.date
FROM payments RIGHT OUTER JOIN withdrawals
  ON payments.client= withdrawals.client
Order by date
于 2013-04-15T07:54:46.790 回答