我知道这有点复杂,我可以用其他方法完成这个,但请耐心等待。
我正在尝试加入一个充满日期的表格,其中包含一个充满事件的表格,因此我可以显示没有事件的日期。我写了一个处理这个问题的QUERY,但是如果我在特定日期有多个事件,我似乎无法加入多个记录。我尝试了所有连接的变种。
请查看我的问题here
SELECT @RowNumber := @RowNumber + 1 AS DayNumber, D.Date, L.LessonID, L.Title
FROM dates D
JOIN (SELECT @RowNumber:= 0) R
LEFT JOIN lessons L ON L.DayNumber = (@RowNumber+1)
WHERE D.Date IN ('2012-01-01','2012-01-03','2012-01-05','2012-01-10')
ORDER BY DayNumber ASC LIMIT 0, 50
CREATE TABLE IF NOT EXISTS `dates` (
`DateID` int(11) NOT NULL AUTO_INCREMENT,
`Date` date NOT NULL,
`TimeStamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`DateID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `dates` (`DateID`, `Date`, `TimeStamp`) VALUES
(1, '2012-01-01', '2013-02-16 17:38:07'),
(2, '2012-01-02', '2013-02-16 17:38:07'),
(3, '2012-01-03', '2013-02-16 17:38:07'),
(4, '2012-01-04', '2013-02-16 17:38:07'),
(5, '2012-01-05', '2013-02-16 17:38:07'),
(6, '2012-01-06', '2013-02-16 17:38:07'),
(7, '2012-01-07', '2013-02-16 17:38:07'),
(8, '2012-01-08', '2013-02-16 17:38:07'),
(9, '2012-01-09', '2013-02-16 17:38:07'),
(10, '2012-01-10', '2013-02-16 17:38:07');
CREATE TABLE IF NOT EXISTS `lessons` (
`LessonID` int(11) NOT NULL AUTO_INCREMENT,
`DayNumber` int(11) NOT NULL DEFAULT '0',
`Title` varchar(1024) NOT NULL,
`TimeStamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`LessonID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `lessons` (`LessonID`, `DayNumber`, `Title`, `TimeStamp`) VALUES
(1, 1, 'asdfasdf', '2012-01-01 18:03:21'),
(2, 1, 'qwerqwer', '2012-01-05 18:03:21'),
(3, 3, '12341234', '2012-01-05 18:03:34');
现在这会返回:
DAYNUMBER DATE LESSONID TITLE
1 January, 01 2012 00:00:00+0000 1 asdfasdf
2 January, 03 2012 00:00:00+0000 (null) (null)
3 January, 05 2012 00:00:00+0000 3 12341234
4 January, 10 2012 00:00:00+0000 (null) (null)
但是我希望它能够返回(注意DayNumber 1上的第二行标题为" qwerqwer"):
DAYNUMBER DATE LESSONID TITLE
1 January, 01 2012 00:00:00+0000 1 asdfasdf
1 January, 01 2012 00:00:00+0000 1 qwerqwer
2 January, 03 2012 00:00:00+0000 (null) (null)
3 January, 05 2012 00:00:00+0000 3 12341234
4 January, 10 2012 00:00:00+0000 (null) (null)
答案 0 :(得分:0)
如果我正确理解你的问题,你可以这样做:
SELECT T.DayNumber,
T.Date,
L.LessonId,
L.Title
FROM (
SELECT @RowNumber := @RowNumber + 1 AS DayNumber,
D.Date
FROM dates D
JOIN (SELECT @RowNumber:= 0) R
WHERE D.Date IN ('2012-01-01','2012-01-03','2012-01-05','2012-01-10')
) T LEFT JOIN Lessons L ON
T.DayNumber = L.DayNumber
ORDER BY T.DayNumber ASC LIMIT 0, 50
以下是更新后的Fiddle。
以下是结果:
DAYNUMBER DATE LESSONID TITLE
1 January, 01 2012 00:00:00+0000 1 asdfasdf
1 January, 01 2012 00:00:00+0000 2 qwerqwer
2 January, 03 2012 00:00:00+0000 (null) (null)
3 January, 05 2012 00:00:00+0000 3 12341234
4 January, 10 2012 00:00:00+0000 (null) (null)
顺便说一句 - 在上面的结果中,你的第二个结果有一个课程ID 1 - 我假设你的意思是上述结果中的课程ID 2。