从三个mysql表中选择数据时出错

时间:2012-01-21 10:50:34

标签: mysql sql select

我已经在这个mysql查询上运行了2天。这是场景:

我有两个表:用户和帐户。结构如下:

$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)";

我想做什么:

我想选择超过10,000人的电话号码,并在最近14天或更长时间内付费或结算。

我们如何找到欠款的人:

你什么时候开帐单(假设为50,000)在db中添加一行,如下所示:

insert into accounts (id, userid, type, amount, date_paid) values ('', 'id of the person', 'OWE', 50000, '$date');

当该人付款(假设为20,000)时,还会插入一行:

insert into accounts (id, userid, type, amount, date_paid) values ('', 'id of the person', 'PAY', 20000, '$date');

获得该人的欠款:

所有账单 - 所有付款

我想出了什么:

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

我一直在修改这个查询很长一段时间,我得到的最好的是错误。其中一些是:

  

您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在select max (a1.datetime) as datetime from a1 where a1.userid=u.id) > 14 group by附近使用正确的语法

当我删除它显示的最后一个和子句时:表db.a2不存在。

请问我该怎么办?

1 个答案:

答案 0 :(得分:1)

提示:

  • 如果金额是小数或其他什么
  • 会更好
  • 以负数存储付款,您只需将金额加总即可获得余额

获得余额

SELECT u.id, SUM(CASE WHEN type = 'OWE' 
                 THEN CAST(amount AS DECIMAL(10,2)) 
                 ELSE CAST(amount AS DECIMAL(10,2))*-1 END ) as balance
FROM users u
INNER JOIN accounts a ON u.id = a.userid
GROUP BY u.id 
HAVING balance > 10000

检查电话号码是否至少有5个字符

WHERE CHAR_LENGTH(phone) > 4  

全部+日期

SELECT u.phone, u.id, SUM(CASE WHEN type = 'OWE' 
                 THEN CAST(amount AS DECIMAL(10,2)) 
                 ELSE CAST(amount AS DECIMAL(10,2))*-1 END ) as balance,
             MAX (date_paid) as last_action
FROM users u
INNER JOIN accounts a ON u.id = a.userid
WHERE CHAR_LENGTH(phone) > 4 
GROUP BY u.id 
HAVING balance > 10000 OR DATE_SUB(CURDATE(),INTERVAL 14 DAY) <= last_action