简体   繁体   English

MySQL左连接并带有其他类似条件

[英]MySQL left join with additional like condition

The plan is to left join from the table work to the table project. 该计划是要保留从表工作到表项目的联接。 After this I want to filter the result with the wildcard work.workdate='2013-12-%' - The result should be the work that was done this month in combination with the project 之后,我想用通配符work.workdate ='2013-12-%'过滤结果-结果应该是本月与项目结合完成的工作

Table work 表工作

CREATE TABLE IF NOT EXISTS `work` (
  `idwork` int(11) NOT NULL AUTO_INCREMENT,
  `iduser` int(11) NOT NULL,
  `idproject` int(11) NOT NULL,
  `workdate` varchar(45) NOT NULL,
  `duration` varchar(45) NOT NULL,
  `description` varchar(45) NOT NULL,
  PRIMARY KEY (`idwork`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

Table project 表项目

CREATE TABLE IF NOT EXISTS `project` (
  `idproject` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  `id` int(11) DEFAULT NULL,
  PRIMARY KEY (`idproject`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;

Statement 声明

SELECT * FROM work LEFT JOIN project ON work.idproject=project.idproject AND work.workdate LIKE '2013-12-%';
  • Output: Every row. 输出:每行。 The rows that are not from December 2013 have null values in the project part 2013年12月以外的行在项目部分中具有空值
  • Expected output: Rows only from December 2013 预期产量:仅从2013年12月开始

So where is my problem? 那我的问题在哪里呢? Do I have to use brackets or something like that? 我必须使用方括号之类的东西吗? I searched on Stackoverflow but always found problems where the LIKE was in the JOIN, but that's not what I want. 我在Stackoverflow上进行搜索,但始终发现JOIN中的LIKE存在问题,但这不是我想要的。 The LIKE is an ADDITIONAL condition. 像是附加条件。

SELECT 
    *
FROM
    work
LEFT JOIN
    project
ON
    work.idproject = project.idproject
WHERE
    work.workdate LIKE '2013-12-%';

should do the trick. 应该可以。 You want to join the project by project ID, but filter the work by date. 您想按项目ID加入项目,但按日期过滤工作。 So filtering should be done in WHERE part. 因此,应在WHERE部分进行过滤。

As I understand your problem I think the additional condition should go into the WHERE -clause: 据我了解你的问题,我认为附加条件应进入WHERE -clause:

SELECT * 
FROM work 
LEFT JOIN project ON work.idproject=project.idproject 
WHERE work.workdate LIKE '2013-12-%';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM