0

编辑:这是我的桌子:

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?

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

谢谢

4

3 回答 3

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 示例

于 2012-10-09T13:28:53.360 回答
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

于 2012-10-09T07:36:46.480 回答
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;
于 2012-10-09T08:54:59.847 回答