简体   繁体   中英

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

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
  • Expected output: Rows only from December 2013

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. 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. So filtering should be done in WHERE part.

As I understand your problem I think the additional condition should go into the WHERE -clause:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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