我有简单的查询
SELECT * FROM `month` LEFT JOIN income ON month.idmonth = income.idmonth
我想显示今年每个月的收入,每个月只有一项收入。
我尝试过结合
WHERE YEAR(`created_at`) = YEAR(CURDATE())
但是这个查询只显示 1 行
或删除此行:
WHERE YEAR(`created_at`) = YEAR(CURDATE())
表格显示
|月 |收入 |
|一月 | 13000 |//2018
|一月 | 14000 |//当前年份 2019
|二月 |空|
|马雷特|空|
|四月 |空|
|梅|空|
。 。 .
|十二月 |空|
这就是我想要的
|月 |收入 |
|一月 | 14000 |
|二月 |空|
|马雷特|空|
|四月 |空|
|梅|空|
。 。 .
|十二月 |空|
最佳答案
如果您在左连接上应用 where 子句,那么它的行为就像交集运算。
您可以使用 AND 条件和 ON 条件来代替 where 子句
像下面的查询
CREATE TABLE `bulan` (
`idmonth` int(11) NOT NULL AUTO_INCREMENT,
`month` varchar(50) NOT NULL,
PRIMARY KEY (`idmonth`)
);
insert into `bulan`(`idmonth`,`month`)
values
(1,'januari'),
(2,'februari'),
(3,'maret'),
(4,'april'),
(5,'mei'),
(6,'juni'),
(7,'juli'),
(8,'agustus'),
(9,'september'),
(10,'oktober'),
(11,'november'),
(12,'desember');
CREATE TABLE `income` (
`idincome` int(11) NOT NULL AUTO_INCREMENT,
`sk` int(11) DEFAULT NULL,
`idmonth` int(11) DEFAULT NULL,
`income` int(11) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`idincome`)
);
insert into `income`
(`idincome`,`sk`,`idmonth`,`income`,`created_at`,`updated_at`)
values
(1,110,1,1300,'2019-03-26 08:01:26','2019-03-26 08:01:26'),
(2,110,1,2400,'2020-03-27 09:57:11',NULL);
以下查询将为您提供预期的输出。
SELECT bulan.month, income.income
FROM `bulan`
LEFT JOIN income
ON bulan.idmonth = income.idmonth
and YEAR(`created_at`) = YEAR(CURDATE())
试试这个 Demo
关于mysql - 显示左连接中的所有月份,但仅显示当年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55369398/