什么应该是正确的查询?

时间:2016-06-09 10:02:33

标签: mysql

这是我的疑问:

SELECT
  employee.name,
  employee.type,
  employee.rate,
  work.overtime,
  work.leaves,
  work.ticket
FROM employee
  LEFT JOIN work ON employee.name = work.name
WHERE work.date BETWEEN :date1 and :date2
HAVING employee.type = :type_emp

但它没有用。我想获取特定类型的员工列表,他们的工作状态应该从日期1到日期2显示。

我该怎么做?

4 个答案:

答案 0 :(得分:2)

你试过了吗?

SELECT
  `employee`.name,
  `employee`.type,
  `employee`.rate,
  `work`.overtime,
  `work`.leaves,
  `work`.ticket
FROM `employee`
  LEFT JOIN `work` ON `employee`.name = `work`.name 
                      AND (`work`.date BETWEEN :date1 AND :date2)
WHERE `employee`.type = :type_emp

答案 1 :(得分:0)

SELECT employee.name, employee.type, employee.rate, work.overtime, work.leaves, work.ticket
FROM employee
LEFT JOIN work on employee.name=work.name
  AND work.date between :date1 and :date2 
WHERE employee.type=:type_emp

原版

有两个问题
  • 左边连接表中的where子句条件强制执行 相当于内连接,所以如果日期之间没有工作 然后根本没有列出任何东西。要解决此问题,请将日期过滤移至“加入条件”而不是“where子句”
  • a having子句不能替代where子句; a having子句用于按group by子句产生的聚合值进行过滤。要解决这个问题,只需使用where子句。

还有另一个潜在的问题,因为它不是过滤日期范围的最佳方法,而是以下方法通常更好但是:date2变成了现在使用的“第二天”。

SELECT employee.name, employee.type, employee.rate, work.overtime, work.leaves, work.ticket
FROM employee
LEFT JOIN work on employee.name=work.name
  AND work.date >= :date1 AND work.date < :date2 
WHERE employee.type=:type_emp

答案 2 :(得分:0)

将' '替换为''(不带引号)

答案 3 :(得分:0)

使用AND运算符调用where子句中的两个条件。试试以下

SELECT employee.name, employee.type, 
employee.rate, work.overtime, work.leaves, work.ticket 
FROM employee LEFT JOIN work 
ON employee.name=work.name 
WHERE employee.type=:type_emp AND
work.date between :date1 and :date2