即使数据库中有记录,查询也会显示计数为0

时间:2019-09-09 12:55:01

标签: mysql

我编写了一个查询,该查询将上个月未完成检查的HS_Reps插入表中(由rowcount = 0表示)。这是代码和关联的表:

DELETE
FROM `not_complete`
WHERE 1 = 1;

INSERT INTO `not_complete`
(ID 
,HS_Rep
,rowcount
,HS_Rep_Email)

SELECT p.ID
      ,p.HS_Rep
      ,COUNT(i.Lead_Inspector)
      ,e.Email

FROM projects p

LEFT JOIN employee e
ON p.HS_Rep = e.Lastname_Firstname
LEFT JOIN inspections i
ON p.HS_Rep = i.Lead_Inspector

AND year(i.date) = year(curdate())
AND month(i.date) = month(curdate()) -1
AND i.Type_of_Inspetion = HS_Rep_Monthly

WHERE p.active = "Yes"
GROUP BY p.HS_Rep
HAVING COUNT(i.Lead_Inspector) <1;

检查i:

+----------------+-----------------+--------------------+
| Lead_Inspector |      DATE       | Type_of_Inspection |
+----------------+-----------------+--------------------+
| Bryant, Kobe   | August 1, 2019  | HS_Rep_Monthly     |
| James, Lebron  | August 15, 2019 | HS_Rep_Monthly     |
+----------------+-----------------+--------------------+

项目p:

+----+-----------------+--------+
| ID |     HS_Rep      | Active |
+----+-----------------+--------+
|  1 | Bryant, Kobe    | Yes    |
|  2 | James, LeBron   | Yes    |
|  3 | Jordan, Michael | Yes    |
+----+-----------------+--------+

雇员e:

+--------------------+-------------------+
| Lastname_Firstname |       Email       |
+--------------------+-------------------+
| Bryant, Kobe       | kobe@email.com    |
| James, LeBron      | leBron@email.com  |
| Jordan, Michael    | michael@email.com |
+--------------------+-------------------+

使用上面的代码,我在not_complete表中得到以下结果:

+----+-----------------+----------+-------------------+
| ID |     HS_Rep      | rowcount |   HS_Rep_Email    |
+----+-----------------+----------+-------------------+
|  1 | Bryant, Kobe    |        0 | kobe@email.com    |
|  2 | James, LeBron   |        0 | lebron@email.com  |
|  3 | Jordan, Michael |        0 | michael@email.com |
+----+-----------------+----------+-------------------+

即使有些HS_Reps上个月完成了检查,但它们的行数仍显示为0。

请让我知道需要对代码进行哪些更改,以便出现适当的行数,并且只有未完成检查的行数才会出现在not_complete中。

1 个答案:

答案 0 :(得分:0)

我猜测查询无法“理解”您的日期值。尝试以下操作:

SELECT p.ID
      ,p.HS_Rep
      ,COUNT(i.Lead_Inspector)
      ,e.Email

FROM projects p

LEFT JOIN employee e
ON p.HS_Rep = e.Lastname_Firstname
LEFT JOIN inspections i
ON p.HS_Rep = i.Lead_Inspector

AND YEAR(STR_TO_DATE(REPLACE(i.date,',',''), "%M %d %Y")) = YEAR(CURDATE())
AND MONTH(STR_TO_DATE(REPLACE(i.date,',',''), "%M %d %Y")) = MONTH(CURDATE())-1
AND i.Type_of_Inspetion = 'HS_Rep_Monthly'

WHERE p.active = "Yes"
GROUP BY p.HS_Rep
HAVING COUNT(i.Lead_Inspector) <1;

观察此部分:

AND YEAR(STR_TO_DATE(REPLACE(i.date,',',''), "%M %d %Y")) = YEAR(CURDATE())
AND MONTH(STR_TO_DATE(REPLACE(i.date,',',''), "%M %d %Y")) = MONTH(CURDATE())-1

首先,我使用REPLACE函数删除了逗号,以使日期变为August 1 2019。然后使用这种格式,我使用STR_TO_DATEAugust 1 2019更改为2019-08-01。因此,最终结果将以年(2019)和月(08)为例。您之前的查询返回YEARMONTHNULL,这就是为什么它不起作用的原因。