I have been on this mysql query for 2 days running. This is the scenario:
I have two tables: users and accounts. There structures below:
$sql="create table if not exists users (
id bigint(20) not null auto_increment,
username varchar(255) not null,
password varchar(255) not null,
email varchar(255),
phone varchar(40),
PRIMARY KEY (id, username))";
$sql="create table if not exists accounts (
id int not null auto_increment, primary key(id),
userid int(11) not null,
type varchar(20) not null, <----- we have two types: bill and pay ------>
amount varchar(255) not null,
date_paid datetime not null)";
What I Want To Do:
I want to select the phone numbers of people owing over 10,000 and paid or billed last 14days ago or more.
How do we find people that are owing:
When are you billed (assuming 50, 000) a row is added in the db like this:
insert into accounts (id, userid, type, amount, date_paid) values ('', 'id of the person', 'OWE', 50000, '$date');
When the person makes a pay (assume 20, 000), a row is also inserted:
insert into accounts (id, userid, type, amount, date_paid) values ('', 'id of the person', 'PAY', 20000, '$date');
To get the amount the person is owing:
ALL BILLS – ALL PAYMENTS
What i came up with:
select phone from users u, accounts a1, accounts a2 where u.id=a1.userid and phone != '' and (((select sum(a1.amount) from a1 where a1.userid=u.id and a1.type='owe') - (select sum(a2.amount) from a2 where a2.userid=u.id and a2.type='pay')) >= 10000) and datediff(NOW(), select max (a1.datetime) as datetime from a1 where a1.userid=u.id) > 14 group by u.id
I have been modifying this query for a long time and the best i get are errors. Some of which are:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
select max (a1.datetime) as datetime from a1 where a1.userid=u.id) > 14 group by
When i remove the last and clause it shows: table db.a2 does not exist.
Please how can i go about this?
Hints:
get the balance
check that the phone number has at least 5 character
All together + Date