鉴于这些表
table Channel
--------------
ChannelID int IDENTITY
<other irrelevant stuff>
table Program
--------------
ProgramID int IDENTITY
ChannelID int
AiringDate datetime
<other irrelevant stuff>
这个查询
SELECT C.ChannelID, t.AiringDate
FROM
Channel C
LEFT JOIN (
SELECT distinct ChannelID
FROM Program
WHERE AiringDate = '2010-01-16'
) p
ON p.ChannelID=C.ChannelID
CROSS JOIN (
SELECT AiringDate = '2010-01-16'
) t
WHERE C.ChannelID IN (1, 2, 74, 15, 906) /* the Channel table contains more channels than we are interested in */
AND p.ChannelID IS NULL
产生
ChannelID | AiringDate
----------|-----------
2 | 2010-01-16
906 | 2010-01-16
如何修改它以接受日期范围,以便结果类似于
ChannelID | AiringDate
----------|-----------
2 | 2010-01-16
906 | 2010-01-16
2 | 2010-01-17
906 | 2010-01-17
如果这两天没有在这两个频道播出的节目
这不返回任何行
SELECT C.ChannelID, t.AiringDate
FROM
Channel C
LEFT JOIN (
SELECT distinct ChannelID, AiringDate
FROM Program
WHERE AiringDate between '2010-01-16' and '2010-01-17'
) p
ON p.ChannelID=C.ChannelID
CROSS JOIN (
SELECT AiringDate = '2010-01-16'
union
SELECT AiringDate = '2010-01-17'
) t
WHERE C.ChannelID IN (1, 2, 74, 15, 906)
AND p.ChannelID IS NULL
这CROSS JOIN
有点难看,完全摆脱它会很好。请注意,第一个示例查询有点复杂;对于单个日期,我有一个更简单的日期,它只输出缺少的 ChannelID:
SELECT C.ChannelID
FROM
Channel C
LEFT JOIN (
SELECT distinct ChannelID
FROM Program
WHERE AiringDate = '2010-01-16'
) p
ON p.ChannelID=C.ChannelID
WHERE C.ChannelID IN (1, 2, 74, 15, 906)
AND p.ChannelID IS NULL