没有WHERE子句的MySQL LEFT JOIN不返回空行

时间:2012-10-09 06:54:27

标签: mysql row left-join

编辑: 这是我的表:

CREATE TABLE IF NOT EXISTS `punch` (
  `name` varchar(50) NOT NULL,
  `date` varchar(50) NOT NULL,
  `duration` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `punch` (`name`, `date`, `duration`) VALUES
('foo', '1', 2),
('bar', '1', 3),
('bar', '2', 5),
('foo', '3', 6),
('foo', '4', 8),
('bar', '4', 9);

我的表格值如下:

SELECT * FROM `punch` P1 WHERE P1.date BETWEEN 1 AND 3 ORDER BY P1.name , date;

结果:

name    date    duration
bar        1    3
bar        2    5
foo        1    2
foo        3    6

我想像这样做一个日期1到3的报告:

name    date    duration
bar        1    3
bar        2    5
bar        3    null
foo        1    2
foo        2    null
foo        3    6

我尝试了这个查询(请注意注释的WHERE):

SELECT * FROM (
    SELECT DISTINCT date FROM punch WHERE date BETWEEN 1 AND 3
) P1
LEFT JOIN (
    SELECT * FROM punch -- WHERE name = 'bar'
) P2 ON P1.date=P2.date

ORDER BY P2.name, P1.date

我得到了结果:

date    name    date    duration
1       bar     1       3
2       bar     2       5
1       foo     1       2
3       foo     3       6

我期待的是:

date    name    date    duration
2       NULL    NULL    NULL
3       NULL    NULL    NULL
1       bar     1       3
2       bar     2       5
1       foo     1       2
3       foo     3       6

现在,当我删除评论的WHERE时,我得到了结果:

date    name    date    duration
3       NULL    NULL    NULL
1       bar     1       3
2       bar     2       5

我的问题是,为什么LEFT JOIN在上面没有WHERE子句时表现得像INNER JOIN?

上面我预期报告的正确查询是什么?

由于

3 个答案:

答案 0 :(得分:1)

你喜欢这样的事情:)

 SELECT DISTINCT 
    P1.name, 
    P2.date,
    (SELECT PP.duration 
     FROM punch PP 
       WHERE P1.name = PP.name
         AND P2.date = PP.date ) AS duration
    FROM
      (SELECT DISTINCT name FROM  `punch`) P1,
      (SELECT DISTINCT date FROM punch)P2
        WHERE P2.date BETWEEN 1 AND 3
        ORDER BY P1.name , P2.date

结果:

NAME    DATE    DURATION
bar        1    3
bar        2    5
bar        3    (null)
foo        1    2
foo        2    (null)
foo        3    6

<强> SQLFIDDLE example

答案 1 :(得分:0)

尝试以下方法:

SELECT * FROM (
    SELECT DISTINCT date FROM punch WHERE date BETWEEN 1 AND 3
) P1
LEFT OUTER JOIN (
    SELECT * FROM punch  WHERE name = 'bar'
) P2 ON P1.date=P2.date

OUTER JOIN应该回答您的问题。它包括第二个表中的非匹配元素。

在此处查看有关其工作原理的更多信息:http://infogoal.com/sql/sql-outer-join.htm

答案 2 :(得分:0)

使用日期编号创建附加表,并使用此表加入punch表。

CREATE TABLE days(day_num INT(11));

INSERT INTO days(day_num) VALUES (1),(2),(3),(4),(5);

如果需要,添加更多记录


结果查询 -

SELECT p.* FROM days d
LEFT JOIN punch p
  ON p.date = d.day_num
WHERE
  d.day_num BETWEEN 1 AND 3
ORDER BY
  p.name, p.date;