php - Getting data from multiple tables in sql -
table 1: invoices (inv_id, inv_value, cust_id)
table 2: customers (cust_id, sales_rep)
table 3: members (member_id, member_cateogry, member_type, cust_id)
note 1: each customer pays multiple invoices. (one-to-many relationship).
note 2: each customer pays one-or-more members (so more 1 member related 1 customer).
note 3: each member has category 1 "represents individual" or 2 "represents group".
note 4: each member has type 1 "represents new" or 2 "represents renew".
i want total of invoice_value
field customers who's sales_rep
= 1 , member_category
= 10 , members_type
= 123
ex: total amount of invoices customers paid if sales_rep these customers 1 , members paid new , individual members.
i tried:
select sum(invoices.inv_value) total invoices, customers, members invoices.cust_id = customers.cust_id , members.custid = customers.cust_id , members.category = {$category} , members_type = {$type} , customers.sales_rep = {$id}";
and
select sum(invoices.inv_value) total members inner join customers on members.custid = customers.cust_id inner join invoices on customers.cust_id = invoices.cust_id customers.sales_rep = {$id} , members.category = {$category} , members.type = {$type}";
but both return double invoice value.
ex.: 1 invoice $120 in invoices table return $240 using these sql queries.
why happen , how fix ???
in advance
this query:
select sum(i.inv_value) total members m inner join customers c on m.custid = c.cust_id inner join invoices on c.cust_id = i.cust_id c.sales_rep = {$id} , m.category = {$category} , m.type = {$type}";
(don't use implicit join
syntax using commas. archaic , less powerful.)
the problem 2 members can have same customer id. can check running:
select m.cust_id, count(*) members m group m.cust_id having count(*) > 1;
it possible customer ids duplicated in customers
.
assuming duplicates in members
, change query exists
:
select sum(i.inv_value) total customers c on inner join invoices on c.cust_id = i.cust_id c.sales_rep = {$id} , exists (select 1 members m m.custid = c.cust_id , m.category = {$category} , m.type = {$type} );
Comments
Post a Comment