避免在列中重复数据

时间:2014-11-13 13:53:33

标签: mysql sql

我有3张桌子,所有桌子都与PK和FK联系在一起。表格为acc_details,acc_info,acc_bill

TABLE : acc_info

ID     |    acc_no         |  rate
______________________________________
1      |         00001     |     0
2      |         00002     |     21
3      |         00003     |     21
4      |         00004     |     21 

TABLE : acc_details

id_dls |    acc_type       |  address         |  **ID**
________________________________________________________
1      |        store      |     pekan        |  1
2      |     water plant   |     raub         |  1
3      |       store       |     kuantan      |  2
4      |      pump house   |     temerloh     |  2


TABLE : acc_bill

id_bill |        acc_no    |  charge_1        |  charge_2
________________________________________________________
1       |       00001      |     20.00        |  12.00
2       |       00002      |     15.00        |  16.00

PK ---> ID,acc_no FROM acc_info FK ---> ID FROM acc_details,acc_no FROM acc_bill

我希望结果是这样的

address     |    acc_type       |    acc_no       |     charge_1  | charge_2
_________________________________________________________________________________
pekan       |    store          |    00001        |      20.00    |   12.00
raub        |    water plant    |                 |               |   
kuantan     |    store          |    00002        |      15.00    |   26.00
temerloh    |    pump house     |                 |               |

但是从我查询的结果来看,acc_no / charge_1 / charge_2会重复,因此当我按SUM(charge_1)

时会出现问题

如何解决这个问题?

更新

  $result = mysql_query("SELECT address , acc_type , acc_bill.acc_no , charge_1 , charge_2 
                        FROM   acc_info , acc_details , acc_bill
                        WHERE  acc_info.id = acc_details.id 
                        AND acc_info.acc_no = acc_bill.acc_no 
                        AND month ='".$month."' 
                        AND acc_category= 'Telekom Malaysia'" ); 

$result1 = mysql_query
("SELECT SUM(charge_1) AS Total_1 , 
         SUM(charge_2) AS Total_2
FROM   acc_info , acc_details , acc_bill
                        WHERE  acc_info.id = acc_details.id 
                        AND acc_info.acc_no = acc_bill.acc_no 
                        AND month ='".$month."' 
                        AND acc_category= 'Telekom Malaysia'" );

1 个答案:

答案 0 :(得分:0)

UNTESTED:但也许这就是......

SELECT address, acc_Type, acc_no charge_1, charge_2
FROM acc_info AI
INNER JOIN acc_Details AD
 on AI.ID = AD.ID
LEFT JOIN acc_bill AB
 on AI.acc_no = AB.Acc_no
 AND AD.acc_Type = 'store'
ORDER BY AI.ID, AD.id_DLS

如果,您所追求的是前两个表中的所有记录,并且只有当第二个表中的记录属于acc_Type存储时,在第3个中匹配的记录,然后使用左连接到第三个表并且仅加入商店类型应该这样做。

我假设商店是一个独特的限定符,如果它不是,你只是匹配第二个表中的一个条目,并且无关紧要,这有点复杂,因为我们必须得到该子集的最小或最大ID。