无法在where子句中使用嵌套查询进行选择

时间:2016-10-13 09:24:34

标签: mysql

首先,我想从bill_client中选择一些列,从bill_pkg中选择一列,这很简单,如下所示:

查询:

SELECT c.company_id, c.client_id, p.pkg_rate
FROM bill_client c
JOIN bill_pkg p on c.pkg_id=p.pkg_id
WHERE c.status=1

我实际上尝试选择extract(year_month from curdate())>

SELECT c.company_id, c.client_id, p.pkg_rate
FROM bill_client c
JOIN bill_pkg p on c.pkg_id=p.pkg_id
WHERE c.status=1 and extract(year_month from curdate())>
 (SELECT MAX(due_month)
 FROM bill_rent
 WHERE c.client_id=client_id and c.company_id=company_id
 GROUP BY client_id, company_id)

但是此查询仅返回client_idbill_rent表匹配的行,而不是bill_client表中的所有行。我需要检查当前月份company_id是否存在client_idbill_rentdue_month。请帮忙。

这是表格架构:

tabll:的 bill_client

CREATE TABLE `bill_client` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `client_id` varchar(30) NOT NULL,
 `client_name` varchar(50) NOT NULL,
 `address` varchar(100) NOT NULL,
 `opening_balance` decimal(10,2) NOT NULL,
 `conn_charge` decimal(13,2) NOT NULL,
 `con_date` date NOT NULL,
 `mobile` varchar(12) NOT NULL,
 `pkg_id` int(11) NOT NULL,
 `conn_type` int(11) NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1',
 `area_id` int(11) NOT NULL,
 `managed_by` int(11) NOT NULL,
 `remarks` varchar(100) NOT NULL,
 `photo` varchar(50) DEFAULT NULL,
 `company_id` varchar(15) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=165 DEFAULT CHARSET=utf8

表:的 bill_pkg

CREATE TABLE `bill_pkg` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `pkg_id` int(11) NOT NULL,
 `pkg_name` varchar(10) NOT NULL,
 `pkg_rate` decimal(10,0) NOT NULL,
 `company_id` varchar(15) NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `pkg_name` (`pkg_name`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8

表:的 bill_rent

CREATE TABLE `bill_rent` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `company_id` varchar(15) NOT NULL,
 `client_id` varchar(10) NOT NULL,
 `due_month` varchar(6) NOT NULL,
 `pay_date` date NOT NULL,
 `amount_due` decimal(10,2) NOT NULL,
 `amount_paid` decimal(10,2) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8

1 个答案:

答案 0 :(得分:1)

如果client_id与bill_rent表格不匹配,则MAX(due_month)将为NULL,因此将当前月份与此进行比较将失败。使用IFNULL(MAX(due_month), ''),以便始终获得与之比较的有效值。

SELECT c.company_id, c.client_id, p.pkg_rate
FROM bill_client c
JOIN bill_pkg p on c.pkg_id=p.pkg_id
WHERE c.status=1 and extract(year_month from curdate())>
 (SELECT IFNULL(MAX(due_month), '')
 FROM bill_rent
 WHERE c.client_id=client_id and c.company_id=company_id)