MySQL连接表重复值

时间:2017-09-27 20:48:48

标签: mysql sql

表格

姓名:_close_checks

+-------------+-------+---------+------------+
|   check_id  | Net   | Gross   |    Tax     |
+-------------+-------+---------+------------+
|       11111 | 100   | 210     |    10      |
|       22222 | 200   | 220     |    20      |
|       33333 | 200   | 300     |    100     |
+-------------+-------+---------+------------+

名称:_close_payment_type

+-------------+--------------+----------------+
|   check_id  | payment_type | payment_amount |
+-------------+--------------+----------------+
|       11111 |    Cash      |       110      |
|       11111 |    Visa      |       100      |
|       22222 |    Cash      |       220      | 
|       22222 |    Cash      |       300      |   
+-------------+--------------+----------------+

我使用以下代码加入表:

Select  *
From _close_payment_type
  Inner Join _close_checks On _close_checks.check_id = _close_payment_type.check_id

我得到的结果:

+-------------+-------+---------+------------+--------------+----------------+
|   check_id  | Net   | Gross   |    Tax     | payment_type | payment_amount |
+-------------+-------+---------+------------+--------------+----------------+
|       11111 | 100   | 210     |    10      |    Cash      |       110      |
|       11111 | 100   | 210     |    10      |    vISA      |       100      |
|       22222 | 200   | 220     |    20      |    Cash      |       220      | 
|       33333 | 200   | 300     |    100     |    Cash      |       300      |   
+-------------+-------+---------+------------+--------------+----------------+

您会看到重复的净值 - 支票号码11111的总税额

我想要的结果:

+-------------+-------+---------+------------+--------------+----------------+
|   check_id  | Net   | Gross   |    Tax     | payment_type | payment_amount |
+-------------+-------+---------+------------+--------------+----------------+
|       11111 | 100   | 210     |    10      |    Cash      |       110      |
|       11111 |   -   |   -     |     -      |    vISA      |       100      |
|       22222 | 200   | 220     |    20      |    Cash      |       220      | 
|       33333 | 200   | 300     |    100     |    Cash      |       300      |   
+-------------+-------+---------+------------+--------------+----------------+

抱歉我的英语不好,谢谢

2 个答案:

答案 0 :(得分:0)

这不称为重复数据,因为付款类型和金额不同。您可以获取数据并在代码中以您希望的方式显示数据。

答案 1 :(得分:0)

根据您的最终目标,您可以做一些简单的事情

Select _close_payment_type.check_id, IF(payment_type='Visa','-',Net) AS Net, IF(payment_type='Visa','-',Gross) AS Gross, IF(payment_type='Visa','-',Tax) AS Tax, payment_type, payment_amount From _close_payment_type Inner Join _close_checks On _close_checks.check_id = _close_payment_type.check_id;

这确实会导致数据以您想要的方式显示,但可能不是最佳方式。了解您正在尝试解决的实际问题会更有帮助。