2012-01-21 2 views
0

2 일 동안이 mysql 쿼리를 실행했습니다. 이 시나리오는 다음과 같습니다.세 개의 mysql 테이블에서 데이터를 선택하는 중 오류가 발생했습니다.

사용자와 계정이라는 두 개의 테이블이 있습니다. 아래에이 구조 :

나는 10,000 때문에 사람들의 전화 번호를 선택합니다 및 유료 또는 십사일 전에 이상 지난 청구 : 내가 원하는 무엇

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

.

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

은 사람이 만드는 경우 : 당신이 행은 다음과 같이 DB에 추가됩니다 (50, 000 가정)이 청구하는 경우

을 :

는 우리가 어떻게 때문에 사람들을 찾을 수 있습니까 유료 (20 000 가정)를, 행은 삽입됩니다

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

이 사람이 때문에되는 양을 얻으려면 :

ALL 청구서 - 내가 해낸 모든 지불

:

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 구문에 오류가 있습니다. 테이블 db.a2가 존재하지 않습니다 : 내가 마지막을 제거하면 올바른 구문은 select max (a1.datetime) as datetime from a1 where a1.userid=u.id) > 14 group by

근처에서 사용하고 절은이 쇼 MySQL 서버 버전에 해당하는 설명서를 확인.

어떻게하면 좋을까요?

답변

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 

그는 전화 번호

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 
+0

가 정말 감사합니다 모두 함께 문자

WHERE CHAR_LENGTH(phone) > 4 

을 + 날짜 적어도 5있다! 훌륭해. 몇 명의 운영자를 변경했습니다. 다시 한번 감사합니다 –

관련 문제