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

标签 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

我实际上尝试选择 with where 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_idclient_id 是否存在 bill_rentdue_month 列。请提供任何帮助。

这是表架构:

表格: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

最佳答案

如果 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)

关于mysql - 无法在 where 子句中使用嵌套查询进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40017101/

相关文章:

Mysql时间戳查询插入

MySQL删除子查询中的重复子句

mysql - Sql 查询获取无效条目

mysql - SQL:获取与日期时间最近的 N 行

mysql - 数据库设计 : Register and Verification

mysql - 错误 1396 (HY000) : Operation CREATE USER failed for 'username' @'localhost' IDENTIFIED BY 'mypassword' ;

mysql - 根据位置和附加数据选择

MySQL Workbench 6.3.7 在使用 Windows 10 Home 进行查询时崩溃

php - Insert Join with limit - Mysql

php - Laravel MySQL 无法在可为空的外键中插入空值