MYSQL LEFT JOIN结果没有给出

时间:2016-10-10 12:25:22

标签: mysql

我有2张桌子

银行表

create table `banks` (
    `bank_id` int ,
    `bank_name` varchar (150),
    `balance` double ,
    `b_date` date ,
    `delete_state` double 
); 
insert into `banks` (`bank_id`, `bank_name`, `balance`, `b_date`, `delete_state`) values('1','Emirates NBD','632008','2016-10-10','0');
insert into `banks` (`bank_id`, `bank_name`, `balance`, `b_date`, `delete_state`) values('3','HABIB BANK LIMITED','1134484','2016-10-10','0');

检查表

create table `cheque` (
    `ch_id` int ,
    `bank_id` int ,
    `amount` double ,
    `status` int,
    `delete_state` double 
); 
insert into `cheque` (`ch_id`, `bank_id`,  `amount`, `status`, `delete_state`) values('4','1','15000','2','0');
insert into `cheque` (`ch_id`, `bank_id`,  `amount`, `status`, `delete_state`) values('9','1','250000','1','0');

我的MYSQL查询

SELECT bk.*,  SUM(amount) AS tot_amount, (bk.balance - SUM(amount)) AS bank_balance FROM banks bk LEFT JOIN cheque ch ON bk.bank_id = ch.bank_id 
WHERE ch.status = 1 AND bk.delete_state=0 AND ch.delete_state = 0 

我需要加入这两张表并从银行表中获取所有bank_name,即使检查表没有任何条目..

但是当前我的查询是在检查表只有条目时给出,所以它只返回一个银行结果..请检查并让我知道我在哪里失踪!!

2 个答案:

答案 0 :(得分:2)

您需要按bank_id分组。当您对问题进行分组时,您将获得所分组变量的每个值的结果。

SELECT bk.*, SUM(amount) AS tot_amount, (bk.balance - SUM(amount)) AS bank_balance 
FROM banks bk 
LEFT JOIN cheque ch ON (bk.bank_id = ch.bank_id  AND ch.status = 1 AND ch.delete_state = 0)
WHERE bk.delete_state=0 
GROUP BY bk.bank_id;

SQL Fiddle

答案 1 :(得分:0)

试试这个:

SELECT bk.*,  
       SUM(CASE WHEN bk.delete_state=0 THEN amount ELSE 0 END) AS tot_amount, 
       SUM(CASE WHEN bk.delete_state=0 THEN bk.balance ELSE 0 END) 
        - 
       SUM(CASE WHEN bk.delete_state=0 THEN amount ELSE 0 END) AS bank_balance 
FROM banks bk 
LEFT JOIN cheque ch ON bk.bank_id = ch.bank_id AND ch.status = 1 AND ch.delete_state = 0
GROUP BY bk.`bank_id`, bk.`bank_name`

一些注意事项:

  • 查询使用GROUP BY子句,因此a按bank_id返回单独的记录。
  • cheque表相关的谓词已从WHERE移至ON子句。否则,LEFT JOIN将成为INNER JOIN
  • 查询使用条件聚合,以便考虑与bk.delete_state=0的银行相关的记录。